zoukankan      html  css  js  c++  java
  • 数组的扩展

    1 Array.from()

    Array.from方法用于将两类对象转为真正的数组:类似数组的对象和可遍历的对象

    demo

    let arrayLike = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        length: 3
    };
    
    // ES5的写法
    var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
    
    // ES6的写法
    let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

    实际应用中,常见的类似数组的对象是DOM操作返回的NodeList集合,以及函数内部的arguments对象。Array.from都可以将它们转为真正的数组。

    // NodeList对象
    let ps = document.querySelectorAll('p');
    Array.from(ps).forEach(function (p) {
      console.log(p);
    });
    
    // arguments对象
    function foo() {
      var args = Array.from(arguments);
      // ...
    }

    上面代码中,querySelectorAll方法返回的是一个类似数组的对象,可以将这个对象转为真正的数组,再使用forEach方法。

    2 Array.of()

    2 Array.of方法用于将一组值,转换我数组

    Array.of(3, 11, 8) // [3,11,8]
    Array.of(3) // [3]
    Array.of(3).length // 1

    3 copyWithin()

    数组实例的copyWithin()方法,在当前数组内部,将指定位置的成员复制到其他位置,让后返回当前的数据。也就是说,使用这个方法,会修改当前组

    Array.prototype.copyWithin(target, start = 0, end = this.length)

    它接受三个参数。

    • target(必需):从该位置开始替换数据。
    • start(可选):从该位置开始读取数据,默认为0。如果为负值,表示倒数。
    • end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示倒数。

    这三个参数都应该是数值,如果不是,会自动转为数值。

    [1, 2, 3, 4, 5].copyWithin(0, 3)
    // [4, 5, 3, 4, 5]

    数组实例的find()和findIndex() 

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

    [1, 4, -5, 10].find((n) => n < 0)
    // -5

    上面代码找出数组中第一个小于0的成员。

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

    数组实例的fill()

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

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

    上面代码表明,fill方法用于空数组的初始化非常方便。数组中已有的元素,会被全部抹去。

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

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

    上面代码表示,fill方法从1号位开始,向原数组填充7,到2号位之前结束。

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

    数组实例的includes() 

  • 相关阅读:
    iOS13 present VC方法
    青囊奥语
    三元九运的排盘
    三元九运 笔记
    青囊经
    金钱卦起卦
    易经中九二六三是什么意思
    用神
    六爻预测中的世爻,应爻分别代表什么
    div2-1519-D-Maximum Sum of Products-dp
  • 原文地址:https://www.cnblogs.com/xiaofenguo/p/6964328.html
Copyright © 2011-2022 走看看