美文网首页
瞅瞅ES6多好玩——数组篇

瞅瞅ES6多好玩——数组篇

作者: Leonard被注册了 | 来源:发表于2019-12-07 16:50 被阅读0次

    两个类方法

    1.Array.from()

    类数组可遍历对象(包括ES6新增的Set和Map)转换为数组

    // ES5
    var arr = Array.prototype.slice.call(arrayLike);
    // ES6
    let arr = Array.from(arrayLike)  
    // ...展开运算符也可以实现类似操作
    let arr = [...arrayLike];
    

    关于该方法与展开运算符的区别,前者支持任何有length属性的对象,而后者做不到

    Array.from({length: 3})    // [undefined, undefined, undefined]
    [...{length: 3}]           // TypeError: object is not iterable
    

    该方法接受第二个参数用于对每个元素进行处理

    // ES5 map()
    Array.prototype.slice.call([1,2,3]).map(x => x * x)     // [1, 4, 9]
    // ES6
    Array.from([1,2,3], x => x * x)    // [1, 4, 9]
    

    2.Array.of()

    奥义:无论几个参数,统统变成数组的元素,弥补了Array()由于参数个数不同导致的差异行为的不足

    Array.of(3,4,5)  // [3,4,5]
    Array(3,4,5)     // [3,4,5]
    Array.of(3)      // [3]
    Array(3)         // [,,]
    Array.of()       // []
    Array()          // []
    

    实例方法

    1.find()和findIndex()

    如你所想,找到数组成员(后者找数组成员索引值)并返回

    [1,2,3,4].find((value,index,arr)=>value>3)    // 4
    [1,2,3,4].findIndex((value,index,arr)=>value>3)   // 3
    

    可以发现NaN,IndexOf()方法可做不到

    [NaN].indexOf(NaN)                    // -1
    [NaN].findIndex(x=>Object.is(NaN,x))  // 0
    

    2.fill(item, start, end)

    填充数组,方便初始化

    new Array(3).fill(6)    // [6,6,6]
    [1,2,3].fill(6,1,2)     // [1,6,3]
    

    3.includes(item, start)

    检验是否包含某个值

    [2,3,3].includes(2);      // true
    [2,3,NaN].includes(NaN);  // true
    [2,3,4].includes(4,-1)    // true
    

    4.entries()、keys()和values()

    这三个方法用于遍历数组。它们都返回一个遍历器对象,可以用for...of进行遍历

    // 对键名的遍历
    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"
    

    当然也可以手动调用遍历器对象的next方法,进行遍历

    let letters = ['a', 'b', 'c'];
    let entries = letters.entries();
    console.log(entries.next().value); // [0, 'a']
    console.log(entries.next().value); // [1, 'b']
    console.log(entries.next().value); // [2, 'c']
    

    相关文章

      网友评论

          本文标题:瞅瞅ES6多好玩——数组篇

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