JS-数组与字符串的转换

186 阅读1分钟

1.数组=>字符串

join('分隔符号'),将数组中的元素以该符号连接成字符串

const a = [1,2,3,4,5];
const b = a.join('-');
console.log(b); // 1-2-3-4-5

toString(),将数组中的元素转换成字符串以逗号连接返回

const a = [1,2,3,4,5];
const b = a.toString();
console.log(b); // 1,2,3,4,5

toLocaleString(),与toString用法类似,区别是能够使用用户所在地区特定的分隔符把生成的字符串连接起来

const a = [1,2,3,4,5];
const b = a.toLocaleString();
console.log(b); // 1-2-3-4-5

2.字符串=>数组

split('符号') 在字符串的某个符号处进行分解,以数组形式返回

const a = 'abcd#efg';
const b = a.split('#');
const c = a.split('');
console.log(b); //  ['abcd', 'efg']
console.log(c); //  ['a', 'b', 'c', 'd', '#', 'e', 'f', 'g']

[...str]ES6 展开运算符 将字符串展开,以数组形式返回

const a = 'abcd#efg';
const b = [...a];
console.log(b); //  ['a', 'b', 'c', 'd', '#', 'e', 'f', 'g']

[...newArr]=strES6 解构赋值 将字符串剩余部分提取到单个变量中

const a = 'abcd#efg';
const [...b] = a;
console.log(b); //  ['a', 'b', 'c', 'd', '#', 'e', 'f', 'g']

Array.fromES6 将一个类数组对象或者可遍历对象转换成一个真正的数组。

const a = 'abcd#efg';
const b = Array.from(a);
console.log(b); //  ['a', 'b', 'c', 'd', '#', 'e', 'f', 'g']