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

    1、Array.from()

    用于将两类对象转为真正的数组

    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']

    扩展运算符(...)也可以将某些数据结构转为数组

    // arguments 对象
    function foo() {
        var args = [...arguments];
    }

    2、Array.of()

    用于将一组值,转换为数组。

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

    与 Array() 的行为有所区别

    Array(3, 11, 8)    // [3, 11, 8]
    Array(3)           // [, , ,]

    3、copyWithin()

    用于数组实例,在当前数组内部,将指定位置的成员复制到其他位置(覆盖原有成员),然后返回当前数组

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

    它接受三个参数:

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

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

    //  将 3 号位复制到 0 号位
    [1, 2, 3, 4, 5].copyWithin(0, 3, 4)
    // [4, 2, 3, 4, 5]

    4、find()

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

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

    5、findIndex()

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

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

    6、fill()

    使用给定值,填充一个数组

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

    如果接受第二个和第三个参数,用于指定填充的起始位置和结束位置

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

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

    7、keys()

    返回一个数组,成员是对应属性的键名

    for (let index of ['a', 'b'].keys()) {
        console.log(index);
    }
    // 0
    // 1

    8、values()

    返回一个数组,成员是对应属性的键值

    for (let elem of ['a', 'b'].values()) {
        console.log(elem);
    }
    // 'a'
    // 'b'

    9、entries()

    返回一个数组,成员是对应属性的键值对数组

    for (let [index, elem] of ['a', 'b'].entries()) {
        console.log(index, elem);
    }
    // 0 "a"
    // 1 "b"

     

    10、includes()

    判断数组是否包含给定的值,返回布尔值

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

    第二个参数表示搜索的起始位置(默认为 0 )

    [1, 2, 3].includes(3, 3);   // false
    [1, 2, 3].includes(3, -1);  // true
  • 相关阅读:
    lower_bound/upper_bound example
    Counter Mode ( CTR )
    85. Maximal Rectangle
    for_each(c++11)
    Lowest Common Ancestor in a Binary Tree
    python--基础学习(五)参数位置传递、关键字传递、包裹传递及解包裹(*args与**kwargs)
    Python的方法解析顺序(MRO)
    pycharm配置总结
    Python中内置数据类型list,tuple,dict,set的区别和用法
    进程号查找
  • 原文地址:https://www.cnblogs.com/Leophen/p/11208106.html
Copyright © 2011-2022 走看看