一、迭代器方法
在ES6中,Array的原型上提供了三个用于检索数组内容的方法:keys()、values()和entries()。keys()返回数组索引的迭代器,values()返回数组元素的迭代器,而entries()返回索引/值对的迭代器:
let a = [1, 2, 3, 4, 5];let b = ['html', 'css', 'js', 'vue', 'react'];// 输出数组索引,并用Array.from方法转化为数组const a1 = Array.from(a.keys())// 输出数组元素,并用Array.from方法转化为数组const a2 = Array.from(a.values())// 输出数组元素键值对,并用Array.from方法转化为数组const a3 = Array.from(a.entries())console.log(a1); // [ 0, 1, 2, 3, 4 ]console.log(a2); // [ 1, 2, 3, 4, 5 ]console.log(a3); // [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]
使用 ES6 的解构可以非常容易地在循环中拆分键/值对 :
let b = ['html', 'css', 'js', 'vue', 'react'];tips:这里不能用for in 循环,只能用for offor (let [index, value] of b.entries()) {console.log(index);console.log(value);}0html1css2js3vue4react
二、复制和填充方法
ES6 新增了两个方法:批量复制方法 copyWithin(),以及填充数组方法 fill()。这两个方法的 函数签名类似,都需要指定既有数组实例上的一个范围,包含开始索引,不包含结束索引。使用这个方 法不会改变数组的大小。
const zeroes = [0, 0, 0, 0, 0];// 用 5 填充整个数组zeroes.fill(5);console.log(zeroes); // [5, 5, 5, 5, 5]zeroes.fill(0); // 重置// 用 5 填充整个数组zeroes.fill(5);console.log(zeroes); // [5, 5, 5, 5, 5]zeroes.fill(0); // 重置// 用 7 填充索引大于等于 1 且小于 3 的元素zeroes.fill(7, 1, 3);console.log(zeroes); // [0, 7, 7, 0, 0];zeroes.fill(0); // 重置// 用 8 填充索引大于等于 1 且小于 4 的元素// (-4 + zeroes.length = 1)// (-1 + zeroes.length = 4)zeroes.fill(8, -4, -1);console.log(zeroes); // [0, 8, 8, 8, 0];fill()静默忽略超出数组边界、零长度及方向相反的索引范围:const zeroes = [0, 0, 0, 0, 0];// 索引过低,忽略zeroes.fill(1, -10, -6);console.log(zeroes); // [0, 0, 0, 0, 0]// 索引过高,忽略zeroes.fill(1, 10, 15);console.log(zeroes); // [0, 0, 0, 0, 0]// 索引反向,忽略zeroes.fill(2, 4, 2);console.log(zeroes); // [0, 0, 0, 0, 0]// 索引部分可用,填充可用部分zeroes.fill(4, 3, 10)console.log(zeroes); // [0, 0, 0, 4, 4]
与 fill()不同,copyWithin()会按照指定范围浅复制数组中的部分内容,然后将它们插入到指 定索引开始的位置。开始索引和结束索引则与 fill()使用同样的计算方法:
