美文网首页
ES6数组扩展

ES6数组扩展

作者: 时不我与_ | 来源:发表于2020-06-08 08:57 被阅读0次

    ES6 引入了许多有用的数组方法,例如:

    • find(),查找列表中的成员,返回 null 表示没找到
    const array = [{ id: 1, checked: true }, { id: 2,checked: false }];
    array.find(item => item.id === 2 )
    // {id: 2, checked: false}
    
    • findIndex(),查找列表成员的索引如果不存在则返回-1如果存在则返回索引
    array.findIndex(item => item.id === 1)
    // 0
    array.findIndex(item => item.id === 2) 
    // 1
    array.findIndex(item => item.id === 3) 
    //-1
    
    • some(),检查某个断言是否至少在列表的一个成员上为真
    const array = [{ id: 1, checked: false }, { id: 2,checked: false }];
    array.some(item => item.checked)  //false
    
    const array = [{ id: 1, checked: false }, { id: 2,checked: true }];
    array.some(item => item.checked)  //true
    
    • includes,列表是否包含某项
    const array = ['a','b','c','d','e']
    array.includes('a') //true
    array.includes('1') // false
    

    该方法的第二个参数表示搜索的起始位置,默认为 0。如果第二个参数为负数,则表示倒数的位置,如果这时它大于数组长度(比如第二个参数为 -4,但数组长度为 3 ),则会重置为从 0 开始。

    [1, 2, 3].includes(3, 3);  // false
    [1, 2, 3].includes(3, -1); // true
    
    • ES5的数组合并concat(arr1,arr2)、ES6的数组合并[...newArr]
      在ES6以前,我们都是使用concat进行数组的合并或者使用遍历循环的方法。
    const arr1 = ['a', 'b'];
    const arr2 = ['c'];
    const arr3 = ['d', 'e'];
    
    // ES5 的合并数组
    arr1.concat(arr2, arr3);
    
    // ES6 的合并数组
    [...arr1, ...arr2, ...arr3]
    // [ 'a', 'b', 'c', 'd', 'e' ]
    
    • 将字符串转为真正的数组。
    [...'hello']
    // [ "h", "e", "l", "l", "o" ]
    
    • 数组实例的 entries(),keys() 和 values()
      用 for…of 循环进行遍历:
      • keys() 是对键名的遍历
    for (let index of ['a', 'b'].keys()) {
       console.log(index);
     }
    // 0
    // 1
    
    • values() 是对键值的遍历
    for (let elem of ['a', 'b'].values()) {
      console.log(elem);
    }
    // 'a'
    // 'b'
    
    • entries() 是对键值对的遍历。
    for (let [index, elem] of ['a', 'b'].entries()) {
      console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"
    

    相关文章

      网友评论

          本文标题:ES6数组扩展

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