美文网首页
es6数组新方法

es6数组新方法

作者: 坏丶毛病 | 来源:发表于2020-10-30 09:48 被阅读0次

es6提供了3个新方法 —— entries 、keys 、values 用于遍历数组,它们都返回一个遍历器对象,可用for-of循环遍历。

它们唯一的区别在于:

** entries:是对键值对的遍历**

** keys:是对键名的遍历**

** values:是对键值的遍历**

让我们来看下具体操作以及用途:

var arr = ['a', 'b'];

// 遍历键名
for (const index of arr.keys()) {
    console.log(index);
    // 0
    // 1
}

// 遍历键值
for (const element of arr.values()) {
    console.log(element);
    // a
    // b
}

// 遍历键值对
for (const obj of arr.entries()) {
    console.log(obj);
    // [0, "a"]
    // [1, "b"]
}

// 解构遍历键值对
for (const [index, element] of arr.entries()) {
    console.log(index, element);
    // 0 "a"
    // 1 "b"
}

1、遍历键名:这里arr.keys获取到数组遍历器对象(Array Iterator),通过循环得到键名,因为是数组,这里的键名就是下标

2、遍历键值:这里arr.values获取到数组遍历器对象(Array Iterator),通过循环得到键值,最终得到键值

3、遍历键值对:这里arr.entries获取到数组遍历器对象(Array Iterator),通过循环得到键值对数组,通过解构赋值拿到下标和值

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

  let letter = ['a', 'b', 'c'];

  let entries = letter.entries();

  console.log(entries.next().value);

  console.log(entries.next().value);

  console.log(entries.next().value);

效果:

image

好了,以上就是这几个方法的介绍。

如有问题,请指出,接受批评。

相关文章

网友评论

      本文标题:es6数组新方法

      本文链接:https://www.haomeiwen.com/subject/srirvktx.html