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]
  • 相关阅读:
    Unity c# 状态机的简单入门
    python实战教程之自动扫雷(自己存下来学习之用)
    Kubernetes的三种外部访问方式:NodePort、LoadBalancer和Ingress-十一(1)
    Ubuntu安装eclipse以及创建快捷方式
    Dockerfile-HEALTHCHECK指令
    各个版本Microsoft Visual C++运行库下载
    docker 远程连接设置
    centos7安装redis3.2.12
    Windows下允许redis远程访问
    UltraISO制作U盘启动盘-centos7
  • 原文地址:https://www.cnblogs.com/codexlx/p/14280669.html
Copyright © 2011-2022 走看看