js字符串转数组格式的几个方法

170 阅读1分钟
cosnt foo = '12345'

方法一: 字符串split

const result =  foo.split('')
console.log(result) // '1,2,3,4,5'

方法二: 数组扩展运算符

const result = [...foo]
console.log(result) // '1,2,3,4,5'

方法三:数组from 方法

const result = Array.from(foo)
console.log(result) // '1,2,3,4,5'

tip:数组from方法使用 Array.form(arg1,arg2,arg3)

arg1:接受一个类数组 比如[1,2,3,4] 又或者是 '1234' 具体参考js高程第四版

arg2:一个回调函数,相当于执行Array.from().map()方法

arg3:更改this指向

区别于Array.of() of方法接受的是一组参数形式

const foo =  Array.of(1,2,3,4)
console.log(foo) // [1,2,3,4]