数组的扩展
数组实例的entries(),keys()和values()方法
ES6 提供了三个新的方法:entries()
,keys()
和values()
用于遍历数组。
它们都返回一个遍历器对象(Array Iterator),可以用for...of
循环进行遍历,唯一的区别是keys()
是对键名的遍历、values()
是对键值的遍历,entries()
是对键值对的遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | let arr = Array(10)
console.log(arr)
let itr = Array(10).keys()
console.log(itr)
let x1 = [...(Array(10).keys())]
console.log(x1)
let x2 = [...Array(10).keys()]
console.log(x2)
// [ <10 empty items> ]
// Object [Array Iterator] {}
// [
// 0, 1, 2, 3,
// 4, 5, 6, 7,
// 8, 9
// ]
// [
// 0, 1, 2, 3,
// 4, 5, 6, 7,
// 8, 9
// ]
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 | for (let index of ['a', 'b'].keys()) {
console.log(index);
}
for (let elem of ['a', 'b'].values()) {
console.log(elem);
}
for (let [index, elem] of ['a', 'b'].entries()) {
console.log(index, elem);
}
// 0
// 1
// a
// b
// 0 a
// 1 b
|