js 关联数组转字符串
时间: 2023-11-22 09:47:41 浏览: 91
js数组与字符串的相互转换方法
以下是两种将JS关联数组转换为字符串的方法:
1. 使用for循环和字符串拼接的方式:
```javascript
let arr = {name: "John", age: 30, city: "New York"};
let str = "";
for (let key in arr) {
str += key + ":" + arr[key] + ",";
}
str = str.substring(0, str.length - 1); // 去掉最后一个逗号
console.log(str); // 输出:name:John,age:30,city:New York
```
2. 使用toString()方法:
```javascript
let arr = {name: "John", age: 30, city: "New York"};
console.log(Object.entries(arr).toString()); // 输出:name,John,age,30,city,New York
```
阅读全文