var a = 'a,b,c,d';
var arr = [];
arr = a.split(',')
console.log(a) // ['a', 'b', 'c', 'd']
// 定义和用法 (https://www.w3school.com.cn/jsref/jsref_split.asp)
// split() 方法用于把一个字符串分割成字符串数组。
// 2- 字符串数组转逗号隔开的字符串
var ids = [];
var arrlist = [
{ id: 1, name: "王" },
{ id: 2, name: "张" },
];
arrlist.forEach((item) => {
ids.push(item.id);
});
ids = ids.join("==");
console.log(ids, typeof ids); // 1==2 string
// 定义和用法 (https://www.w3school.com.cn/jsref/jsref_join.asp)
// join() 方法将数组作为字符串返回。
// 元素将由指定的分隔符分隔。默认分隔符是逗号 (,)。
// join() 方法可以把数组转换为字符串,不过它可以指定分隔符。在调用 join() 方法时,可以传递一个参数作为分隔符来连接每个元素。如果省略参数,默认使用逗号作为分隔符,这时与 toString() 方法转换操作效果相同。
// 注释:join() 方法不会改变原始数组。
// 3- 单纯的数组转字符串
var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; //定义数组
var s = a.toString(); //把数组转换为字符串
console.log(s); //返回字符串“1,2,3,4,5,6,7,8,9,0”
console.log(typeof s); //返回字符串string,说明是字符串类型
// 4- 两个数组拼接 成一个字符串
var a = [1, 2, 3]; //定义数组
var b = ["name", "age", "weight"]; //定义数组
var s = a + b; //数组连接操作
console.log(s); //返回“1,2,3name,age,weight”
console.log(typeof s); //返回字符串string,说明是字符串类型
// 当数组用于字符串环境中时,JavaScript 会自动调用 toString() 方法将数组转换成字符串。在某些情况下,需要明确调用这个方法。
var a = [[1, ["name", "age"], ["王", "张"]], 6, 7, ["eight", 9], 0]; //定义多维数组
var s = a.toString(); //把数组转换为字符串
console.log(s, typeof s); //返回字符串“1,name,age,王,张,6,7,eight,9,0 string”
// toString() 在把数组转换成字符串时,首先要将数组的每个元素都转换为字符串。当每个元素都被转换为字符串时,才使用逗号进行分隔,以列表的形式输出这些字符串。
userContent = "{"name":"用户姓名","phone":"客户手机号","addr":"地址"}"
字符串转对象
userContent = JSON.parse(userContent )
// userContent = {
// addr: "地址"
// name: "用户姓名"
// phone: "客户手机号"
//}
对象转字符串
JSON.stringify()