美文网首页
es6 Array 新增属性

es6 Array 新增属性

作者: G_whk | 来源:发表于2019-05-15 16:51 被阅读0次
    Array.from()

    Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括ES6新增的数据结构Set和Map)。
    扩展运算符(...)也可以将某些数据结构转为数组。

    // arguments对象
    function foo() {
      var args = [...arguments];
    }
    // NodeList对象
    [...document.querySelectorAll('div')]
    
    Array.of()

    Array.of方法用于将一组值,转换为数组。

    Array.of(3, 11, 8) // [3,11,8]
    Array.of() // []
    Array.of(undefined) // [undefined]
    
    find()和findIndex()

    find方法,用于找出第一个符合条件的数组成员。它的参数是一个回调函数,所有数组成员依次执行该回调函数,直到找出第一个返回值为true的成员,然后返回该成员。如果没有符合条件的成员,则返回undefined。

    [1, 5, 10, 15].find(function(value, index, arr) {
      return value > 9;
    }) // 10
    

    数组实例的findIndex方法的用法与find方法非常类似,返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

    fill()

    fill方法使用给定值,填充一个数组。

    ['a', 'b', 'c'].fill(7)
    // [7, 7, 7]
    

    fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。

    ['a', 'b', 'c'].fill(7, 1, 2)
    // ['a', 7, 'c']
    
    entries(),keys()和values()

    entries(),keys()和values()——用于遍历数组。区别是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"
    
    includes()

    Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似。该方法属于ES7。

    [1, 2, 3].includes(2);     // true
    [1, 2, 3].includes(4);     // false
    [1, 2, NaN].includes(NaN); // true 这个例子用indexOf判断的话就会返回-1,表示不存在。
    

    相关文章

      网友评论

          本文标题:es6 Array 新增属性

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