es6笔记·····entries(),keys(),values()

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

ES6 提供三个新的方法——entries()keys()values()——用于遍历数组。它们都返回一个遍历器对象(详见《Iterator》一章),可以用for...of循环进行遍历,唯一的区别是keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历。

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

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

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
for ( var i of arr.keys()){console.log(i)}
VM1485:1 0
VM1485:1 1
VM1485:1 2
VM1485:1 3
VM1485:1 4
undefined
for ( var i of arr.values()){console.log(i)}
VM1516:1 Uncaught TypeError: arr.values(...)[Symbol.iterator] is not a function
    at :1:20
(anonymous) @ VM1516:1    chrome版本 62.0.3202.75(正式版本) (64 位) firefox也不支持
for ( var i of arr.entries()){console.log(i)}
VM1562:1 (2) [0, 5]0: 01: 5length: 2__proto__: Array(0)
VM1562:1 (2) [1, 5]
VM1562:1 (2) [2, 6]
VM1562:1 (2) [3, 6]
VM1562:1 (2) [4, 6]
undefined
for ( var i of [1,2,3,4].values()){console.log(i)}
VM1569:1 Uncaught TypeError: [1,2,3,4].values(...)[Symbol.iterator] is not a function
    at :1:26
(anonymous) @ VM1569:1
for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
VM1571:1 Uncaught TypeError: ["a","b"].values(...)[Symbol.iterator] is not a function
    at :1:29

如果不使用for...of循环,可以手动调用遍历器对象的next方法,进行遍历。

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']
var arr = [1,2,3,4,5]
undefined
b=arr.entries()
  1. Array Iterator {}
    1. __proto__:Array Iterator
      1. next:ƒ next()
        1. arguments:(...)
        2. caller:(...)
        3. length:0
        4. name:"next"
        5. __proto__:ƒ ()
        6. [[Scopes]]:Scopes[0]
      2. Symbol(Symbol.toStringTag):"Array Iterator"
      3. __proto__:Object
console.log(b.next().value,b.next().value)
VM495:1
  1. (2) [01]
    1. 0:0
    2. 1:1
    3. length:2
    4. __proto__:Array(0)
  1. (2) [12]
    1. 0:1
    2. 1:2
    3. length:2
    4. __proto__:Array(0)
undefined
console.log(b.next(),b.next())
VM606:1
  1. {valueArray(2)donefalse}
    1. done:false
    2. value:(2) [23]
    3. __proto__:Object
  1. {valueArray(2)donefalse}
    1. done:false
    2. value:(2) [34]
    3. __proto__:Object

摘抄自阮一峰文章












你可能感兴趣的:(ecmascript6)