es6新增了一些对数组的操作。
Array.from(),Array.of()
Array.from()用来将类数组转化成数组
类数组的格式是
{'0':'1','1':'2','2':'3',length: 3}正确
{'name':'1','age':'2','color':'3',length: 3}错误
console.log(Array.from({'0':'1','1':'2','2':'3',length: 3}))//[1,2,3]
除了这个作用他还能像map循环一样循环遍历数组进行数组每一项的处理,这个方法传入的第二个参数就是一个方法
console.log(Array.from([1, 2, 3], (x) => x * x))//类似map对每一个项进行处理[1,4,9]
Array.of()将一组值转化成数组(不能转化字符串)
console.log(Array.of(1,3,'f',7,'h',8))//[1,3,f,7,h,8]
es6还提供了其他高效的数组方法
大家都有用过indexOf方法吧,indexOf对比完之后还要对对比的结果进行判断(一般是和-1)
es6提供了includes方法直接返回true或false不用再对结果进行对比
//数组中是否包含某个值(true或false)和indexOf相比不用去比较-1 console.log([1, 2, 3].includes(4),[1, 2, 3].includes(2)) //第二个参数表示从什么位置开始搜索 console.log([1, 2, 3].includes(3, 3),[1, 2, 3].includes(3, 2))
想了一下还是决定将扩展运算符放在这篇文章里面
一般数组合并我们是 arr1.concat(arr2)返回最终合并的数组
扩展运算符的特性是将数组或字符串展开
var str = 'hello' var arr = [1,2,3,4,5,6] var bbb = [12312,...arr,...str]
得到[12312, 1, 2, 3, 4, 5, 6, "h", "e", "l", "l", "o"]相比concat更为直观
push方法不能直接push数组要去写for循环遍历push,但是我们将数组用扩展运算符展开就不用这么麻烦了
arr.push(...str) console.log(arr)
得到[1, 2, 3, 4, 5, 6, "h", "e", "l", "l", "o"]