Arrays to strings, strings to arrays

1. Array to string

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

Two, string to array

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. Spread operator

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

3. Destructuring assignment

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

4.Array.from

Array.from helper creates new arrays from array-like or iterable objects. A string is both iterable and array-like, so it can be successfully converted to a character array

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

Guess you like

Origin blog.csdn.net/Holly31/article/details/130582557