zoukankan      html  css  js  c++  java
  • Array.from的几个用法

    Array.from的一个特性:所有具有length属性的对象,并且key是数字,都能被Array.from转为数组
      // 用法一:对象转数组
            // example 1:
            let obj = {0:'a',1:'b',2:'c',length:3}
           console.log( Array.from(obj) );// [a,b,c]
    // example 2: 这个写法和展开操作符是一样的,为了简便,还是用展开操作符吧
            let div = document.querySelectorAll('div')
            console.log(Array.from(div));
            let divCopy = [...div]
            console.log(divCopy);
            // 用法二:set转数组,使用展开操作符也是一样
            let set  = new Set([1,2,3])
            console.log(Array.from(set));
            let a = [1,2,3]
            let set2 = new Set(...[a])
            console.log([...set2]);
            // 用法三:Array.from的第二个参数,可以遍历数组,相当于map和forEach
            let b = [1,2,3]
            console.log(Array.from(b,v=>v+2)); // [3,4,5]
            Array.from(b).forEach(v=>console.log(v+2))
            Array.from(b).map(v=>console.log(v+2))

    Array.from和Array.of对比

    Array.of是把一组值转换为数组

     Array.of(1,2,3) // [1,2,3]

     

  • 相关阅读:
    899. Orderly Queue
    856. Score of Parentheses
    833. Find And Replace in String
    816. Ambiguous Coordinates
    770. Basic Calculator IV
    冒泡排序(Bubble Sort)
    C
    B
    A
    HDOJ-1391
  • 原文地址:https://www.cnblogs.com/luguankun/p/13708970.html
Copyright © 2011-2022 走看看