ES2015数组扩展

297 阅读3分钟

1、扩展操作符

可以看成rest参数的逆运算


const a1 = [1, 2, 3]
 
console.log(...a1) // 1 2 3
 
// 应用场景:
 
1:复制数组
 
    const arr1 = [1, 2];
 
    const arr2 = [...a1];
 
2:合并数组
    const a1 = [1, 2, 3];
    const a2 = [4, 5, 6];
    const a3 = [7, 8, 9];
 
    ES5写法:a1.concat(a2).concat(a3);
    ES6写法:[...a1, ...a2, ...a3];
3:与解构赋值合用
    const a = [0, 1, 2, 3, 4, 5]
    ES5写法:const a1 = a[0],
                    a2 = a.slice(1);
    ES6写法:const [a1, ...a2] = a;
    

2、Array.from()

将类数组转化为数组


const obj = {
        '0': '哈',
        '1': '嘻',
        '2': '哦',
        '3': '呵',
        'length': 4
      }
      
ES5写法:console.log([].slice.call(obj));
ES6写法:console.log(Array.from(obj));

3、Array.of()

将一组值转化为数组


Array.of(0, 1, '4')
// [0, 1, '4']

4、数组实例的copyWithin()

在数组内部,将指定位置的成员复制到其他位置(替换之前的成员),然后返回当前数组。


const arr = [0, 1, 2, 3, 4, 5, 6];
 
arr.copyWithin(3)
// [0, 1, 2, 0, 1, 2, 3]
 
arr.copyWithin(3, 2)
// [0, 1, 2, 2, 3, 4, 5]
 
arr.copyWithin(3, 2, 4)
// [0, 1, 2, 2, 3, 5, 6]
 
 
// *** 只能分开使用,因为copyWidthin()会改变原数组

5、数组实例的find()和findIndex()

找出第一个符合条件的成员和下标,类似于filter,只不过为第一个


const arr = [0, 1, 2, 3, 4, 7, 6];
 
const temp = arr.find(function(item) {
    return item > 5
})
 
temp    // 7
 
 
const tempIndex = arr.findIndex(function(item) {
    return item > 5
})
 
tempIndex // 5

6、数组实例的fill()

用给定值填充数组,支持三个参数(一:替换的值;二:被替换的开始位置;三:被替换的结束位置


[1, 1,1, 1].fill(88)
 
// [88, 88, 88, 88]
 
 
[1, 1,1, 1].fill(88, 1, 3)
 
// [1, 88, 88, 1]

7、数组实例的entries(), keys(), values()

entries返回数组的键值对 key()返回数组的key值 values()返回数组的值


for (let index of arr.keys()) {
  console.log(index)
}
for(let index of arr.values()) {
    console.log(index)
}
for(let [index, item] of arr.entries()) {
    console.log(index, item)
}

8、数组实例的includes()

Array.prototype.includes返回一个布尔值,表示数组是否有给定的值,与字符串的includes类似。 (ES2016)


const arr = [110, 111, 112, 113, 114, 117, 116];

arr.includes(2)     // false
arr.includes(110)   // true

//第二个参数表示起始搜索的位置

9、数组实例的flat() flatMap()

flat():如果数组中还嵌套着数组,使用flat()将他拉平,变为一维数组,只能拉平一次,根据flat(params)中的param而定拉平几次。
flatMap():对原数组的每个成员执行方法(相当于Array.prototype.map()),然后对返回值组成的数组执行flat()方法。


[1, 2, 3, 4, [1, 2, 5]].flat()      // [1, 2, 3, 4, 1, 2, 5]
[1, 2, 3, 4, [1, 2, [5]]].flat()      // [1, 2, 3, 4, 1, 2, [5]]
[1, 2, 3, 4, [1, 2, [5]]].flat(2)      // [1, 2, 3, 4, 1, 2, 5]

[2, 3, 4].flatMap(x => [x, x * 2])
//  相当于[[2, 4], [3, 6], [4, 8]]
//  [2, 4, 3, 6, 4, 8]

10、数组的空位

数组的空位置代表着数组的某一个位置没有一个数值。(空位置不等于undefined)


const arr = new Array(3)        // [empty, empty, empty]
const arr2 = [, , ,]             // [empty, empty, empty]

ES5对空位的处理不一致
——forEach、filter、reduce、some、every忽略空位。
——map忽略空位,但会保留位置。 ——join()和String()会将空位当做undefined,将undefined和null处理成空字符串 ES6明确将空位转为undefined