ES6 数组扩展(总结)

1、扩展运算符

将一个数组转为用逗号分隔的参数序列

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

2、Array.from()

将两类对象转为真正的数组

类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

 1 let arrayLike = {
 2     '0': 'a',
 3     '1': 'b',
 4     '2': 'c',
 5     length: 3
 6 };
 7 
 8 // ES5的写法
 9 var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
10 
11 // ES6的写法
12 let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

Array.from还可以接受第二个参数,作用类似于数组的map方法,用来对每个元素进行处理,将处理后的值放入返回的数组。

1 Array.from(arrayLike, x => x * x);
2 // 等同于
3 Array.from(arrayLike).map(x => x * x);
4 
5 Array.from([1, 2, 3], (x) => x * x)
6 // [1, 4, 9]

3、Array of()

将一组值,转换为数组。

1 Array.of(3, 11, 8) // [3,11,8]
2 Array.of(3) // [3]
3 Array.of(3).length // 1

4、数组实例的copyWhithin()

在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组.

会修改原的数组

1 Array.prototype.copyWithin(target, start = 0, end = this.length)
  • target(必需):从该位置开始替换数据。如果为负值,表示倒数。
  • start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示倒数。
  • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
1 [1, 2, 3, 4, 5].copyWithin(0, 3)
2 // [4, 5, 3, 4, 5]

上面代码表示将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2。

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

find()  用于找出第一个符合条件的数组成员,找到则返回true,否则返回undefined;

1 [1, 5, 10, 15].find(function(value, index, arr) {
2   return value > 9;
3 }) // 10

find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。

findIndex() 返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

1 [1, 5, 10, 15].findIndex(function(value, index, arr) {
2   return value > 9;
3 }) // 2

这两个方法都可以发现NaN,弥补了数组的indexOf方法的不足.

1 [NaN].indexOf(NaN)
2 // -1
3 
4 [NaN].findIndex(y => Object.is(NaN, y))
5 // 0

6、数组实例的fill()

使用给定值,填充一个数组。

可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。

1 ['a', 'b', 'c'].fill(7, 1, 2)
2 // ['a', 7, 'c']

fill方法从 1 号位开始,向原数组填充 7,到 2 号位之前结束。

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

用于遍历数组

keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

 1 for (let index of ['a', 'b'].keys()) {
 2   console.log(index);
 3 }
 4 // 0
 5 // 1
 6 
 7 for (let elem of ['a', 'b'].values()) {
 8   console.log(elem);
 9 }
10 // 'a'
11 // 'b'
12 
13 for (let [index, elem] of ['a', 'b'].entries()) {
14   console.log(index, elem);
15 }
16 // 0 "a"
17 // 1 "b"

8、数组实例的includes()

返回一个布尔值,表示某个数组是否包含给定的值。

第二个参数表示搜索的起始位置,默认为0。若为负数,则表示倒数位置,若它大于数组长度则重置为0.

1 [1, 2, 3].includes(2)     // true
2 [1, 2, 3].includes(4)     // false
3 [1, 2, NaN].includes(NaN) // true

9、数组的空位

数组的某一个位置没有任何值

1 Array(3) // [, , ,]

ES6 则是明确将空位转为undefined

猜你喜欢

转载自www.cnblogs.com/1032473245jing/p/9115250.html