美文网首页
Array.from()的5种用途

Array.from()的5种用途

作者: 一蓑烟雨任平生_cui | 来源:发表于2019-12-18 16:23 被阅读0次

    介绍Array.from()

    Array.from() 可以将类数组或具有Iterator接口的对象转成数组。接收三个参数,第一个必选参数是arrayLikeOrIterable对象,第二个可选参数类似于数组map方法的回调,第三个可选参数是用来指定回调函数的this(前提是普通函数),很少用到。

    Array.from(arrayLikeOrIterable[, mapFunction[, thisArg]])
    

    Examples

    const arr = { '0': 10, '1': 15, length: 2 }
    
    Array.from(arr, value => value * 2) //  [20, 30]
    

    1. 类数组转数组

    1.1 arguments、NodeList实例、HTMLCollection、具有length属性的对象等

    function sumArguments() {
      return Array.from(arguments).reduce((sum, num) => sum + num)
    }
    
    sumArguments(1, 2, 3) //  6
    

    1.2 具有Iterator接口的对象

    Array.from('Hey')     //  ['H', 'e', 'y']
    Array.from(new Set(['one', 'two'])) //  ['one', 'two']
    
    const map = new Map()
    
    map.set('one', 1)
    map.set('two', 2)
    
    Array.from(map)    //  [['one', 1], ['two', 2]]
    

    Array.from()和 ...(数组扩展运算)的区别:

    ...只能将具有Iterator接口的对象转成数组,而Array.from()还可以转类数组,即便是一个具有length属性的对象{length: 3}

    2. clone数组

    2.1 浅拷贝数组

    const numbers = [3, 6, 9]
    const numbersCopy = Array.from(numbers)
    
    numbers === numbersCopy  // false
    

    2.2 clone多维数组

    function recursiveClone(val) {
      return Array.isArray(val) ? Array.from(val, recursiveClone) : val
    }
    
    const numbers = [[0, 1, 2], ['one', 'two', 'three']]
    const numbersClone = recursiveClone(numbers)
    
    numbersClone // [[0, 1, 2], ['one', 'two', 'three']]
    numbers[0] === numbersClone[0] //  false
    

    3. 填充数组

    const length = 3
    const init   = 1
    const result = Array.from({ length }, () => init) // [ 1, 1, 1]
    

    数组提供了一个fill()方法,当填充的值为复杂类型的值时,和Array.from()的结果是有区别的,具体如下:

    3.1 值为基本类型

    function fillArray(length, init) {
      return Array(length).fill(init)
    }
    
    fillArray(0, 3) //  [0, 0, 0]
    

    3.2 值为复杂类型

    const length = 3
    const resultA = Array.from({ length }, () => ({}))
    const resultB = Array(length).fill({})
    
    resultA  //  [{}, {}, {}]
    resultB  //  [{}, {}, {}]
    
    resultA[0] === resultA[1]  //  false
    resultB[0] === resultB[1]  //  true
    

    resultA每一项的{}不同是因为每次调用map都返回一个新对象。
    而fill()填充的resultB是用同一个实例{}

    3.3 用map()填充呢?

    const length = 3
    const init   = 0
    const result = Array(length).map(() => init)
    
    result // [undefined, undefined, undefined]
    

    map()方法得出结果仍然是一个具有3个空插槽的数组,而不是预期的具有3个0的数组。

    原因是Array(length)创建了一个有3个空槽(也称为稀疏数组)的数组,但是map()在遍历会跳过这些空项(forEach()也是)。

    4 生成一个数字范围的数组

    比如生成一个数组,项从索引开始到结束。

    function range(end) {
      return Array.from({ length: end }, (_, index) => index)
    }
    range(4)  // [0, 1, 2, 3]
    

    5 数组去重

    function unique(array) {
      return Array.from(new Set(array))
    }
    
    unique([1, 1, 2, 3, 3]) // [1, 2, 3]
    

    总结

    Array.from()可以将类数组和具有Iterator接口的对象转成数组,并且参数二实现了类似数组的map()功能,和数组方法的区别是这个方法不会跳过值为 empty的元素。

    相关文章

      网友评论

          本文标题:Array.from()的5种用途

          本文链接:https://www.haomeiwen.com/subject/ihttnctx.html