zoukankan      html  css  js  c++  java
  • Array.from()与Array.of()

    创建一个数组的方式,除了Array构造函数方式(new Array())和数组字面量方式([1,2,3])的方式,还有ES6新增的用于创建数组的静态方法:from()和of()

    1.from()

    Array.from()的第一个参数是一个类数组对象,即任何可迭代的结构,或者有一个length属性和可索引元素的结构。

    常见使用场合:

    • 拆分字符串:
      • let s = "hello"
        console.log(Array.from(s))    // ["h", "e", "l", "l", "o"]
    • 对现有数组进行浅复制:
      • let a1 = [1, 2, 3]
        let a2 = Array.from(a1)
        console.log(a1 === a2)    // false
    • arguments对象转化为数组:
      • function add(){
            console.log(Array.isArray(arguments));    // false
            let arr = Array.from(arguments)
            console.log(Array.isArray(arr));    // true
        }
        
        add([1,2,3])

     2.of()

    Array.of()可以把一组参数转换为数组,用于替代在ES6之前常用的Array.prototype.slice.call(arguments)

    console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] 
    console.log(Array.of(undefined)); // [undefined]
  • 相关阅读:
    739. Daily Temperatures
    535. Encode and Decode TinyURL
    811. Subdomain Visit Count
    706. Design HashMap
    C++-static作用(转)
    大学四年应当如何渡过(转)
    计算机导论第八章-总结
    计算机导论第四章习题
    计算机导论-第一章习题
    20世纪最伟大的十大算法
  • 原文地址:https://www.cnblogs.com/codexlx/p/14280669.html
Copyright © 2011-2022 走看看