1、字符串 -> 数组
let string = '123,456,789';
let stringResult1 = string.split(',');
let stringResult2 = string.split(",").map(Number);
let stringResult3 = JSON.parse("[" + string + "]");
console.log(stringResult1); //输出["123", "456", "789"]
console.log(stringResult2); //输出[123,456,789]
console.log(stringResult3); //输出[123,456,789]
let string2 = 'abcdef';
let string2Result = string2.split('');
console.log(string2Result); //输出['a','b','c','d','e','f']
JSON.parse(参数), 参数为一个有效的json字符串。
如果从服务端接收的是数组的 JSON 数据,则 JSON.parse 会将其转换为 JavaScript 数组。如上面代码中:JSON.parse("[" + string + "]");
2、数组 -> 字符串
let string2 = 'abcdef';
let string2Result1 = string2.split('');
let string2Result2 = [...string2]; //扩展运算符
let string2Result3 = Array.from(string2);
console.log(string2Result1); //输出['a','b','c','d','e','f']
console.log(string2Result2); //输出[ 'a', 'b', 'c', 'd', 'e', 'f' ]
console.log(string2Result3); //输出['a','b','c','d','e','f']