数组转字符串、字符串转数组那些事儿

一、数组转字符串

1.toString

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

2. join()

var a = [1,2,3,4,5];  //定义数组
var s = a.join("|");  //指定分隔符
console.log(s);  //返回字符串 1|2|3|4|5

二、字符串转数组

1.split

var str = "aaa,bbb,ccc";
strArr = str.split(",");// 在每个逗号(,)处进行分解  ["aaa", "bbb", "ccc"]
var hello = "helloworld";
helloArr = hello.split('');  //["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]

2.扩展运算符

const text = "abc????";
const chars = [ ...text ];
console.log(chars);//["a", "b", "c", "?", "?", "?", "?"]

3.解构赋值

const text = "abc????";
const [ ...chars ] = text;
console.log(chars);//["a", "b", "c", "?", "?", "?", "?"]

4.Array.from

Array.from辅助创建从阵列状或迭代的对象的新数组。字符串既可迭代又类似于数组,因此,可以成功地将其转换为字符数组

const text = "abc????";
const chars = Array.from(text);
console.log(chars);//["a", "b", "c", "?", "?", "?", "?"]

猜你喜欢

转载自blog.csdn.net/Holly31/article/details/130582557
今日推荐