ES6 在数组上改变还是比较多的,主要是为了弥补 ES5 一些方法的不足或新增一些方法,但大体这些方法在其他语言中也都见过,所以操作和使用起来不难,可能名字不一样,但看一看就知道如何使用了。

Array.from() 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
const arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
'length': 3
};

// ES6 写法
let arr1 = Array.from(arrayLike);

arr1.forEach((arr) => {
console.log(arr);
})

从字符串中初始化一个数组

1
2
3
let arr2 = Array.from('Hello');
console.log(arr2);
// [ 'H' 'e' 'l' 'l' 'o' ]

从 Set 结构中初始化一个数组

1
2
3
let arr3 = Array.from(new Set(['a', 'b', 'c', 'd']));
console.log(arr3);
// [ 'a' 'b' 'c' 'd' ]

转换一个表明了有 length 属性的对象,由于仅指定了长度为 3,而 3 个元素均没有表明,所以都是 undefined。

1
2
3
let arr4 = Array.from({length: 3});
console.log(arr4);
// [ undefined, undefined, undefined ]

Array.of() 方法

1
2
let arr5 = Array.of(1, 2, 3, 4, 5);
console.log(arr5);

copyWithin() 方法

将指定位置的元素复制到当前数组的指定位置,就是会改变原数组的内容

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

find() 方法

1
2
3
4
5
6
7
8
9
const testArr = [1, 3, -5, 10];

// 找小于 0 的元素
console.log(testArr.find((n) => n < 0));

// 找大于 9 的元素
console.log(testArr.find((value, index, arr) => {
return value > 9;
}));

keys() values() entries()

1
2
3
4
5
6
7
8
9
10
11
for (let index of ['a', 'b', 'c'].keys()) {
console.log(index);
}

for (let elem of ['a', 'b', 'c'].values()) {
console.log(elem);
}

for (let [index, elem] of ['a', 'b', 'c'].entries()) {
console.log(`${index}: ${elem}`);
}