ES6 在数组上改变还是比较多的,主要是为了弥补 ES5 一些方法的不足或新增一些方法,但大体这些方法在其他语言中也都见过,所以操作和使用起来不难,可能名字不一样,但看一看就知道如何使用了。
Array.from() 方法
1 | const arrayLike = { |
从字符串中初始化一个数组
1 | let arr2 = Array.from('Hello'); |
从 Set 结构中初始化一个数组
1 | let arr3 = Array.from(new Set(['a', 'b', 'c', 'd'])); |
转换一个表明了有 length 属性的对象,由于仅指定了长度为 3,而 3 个元素均没有表明,所以都是 undefined。
1 | let arr4 = Array.from({length: 3}); |
Array.of() 方法
1 | let arr5 = Array.of(1, 2, 3, 4, 5); |
copyWithin() 方法
将指定位置的元素复制到当前数组的指定位置,就是会改变原数组的内容
- target(必需):从该位置开始替换数据。
- start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
- end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。
1 | [1, 2, 3, 4, 5].copyWithin(0, 3); |
find() 方法
1 | const testArr = [1, 3, -5, 10]; |
keys() values() entries()
1 | for (let index of ['a', 'b', 'c'].keys()) { |