Array.from():将一个*类数组对象*或*可遍历对象*转换成真正的*数组*

类数组/伪数组:按照索引存储数据,且有length属性的对象

  • 类数组对象转换为真正的数组
  • let arrayLike = {
        0: 'tom', 
        1: '65',
        2: '男',
        3: ['jane','john','Mary'],
        'length': 4
    }
    let arr = Array.from(arrayLike)
    // ["tom", "65", "男", ['jane','john','Mary']]
    
    // ES5的写法
    // [].slice.call(arrayLike)
    
  • 函数内部的arguments对象转为真正的对象

  • function foo () {
        var args = Array.from(arguments)
    }
    
  • Set结构的数组转为真正的数组

  • let set = new Set([1, 2, 3, 2])
    let arr1 = Array.from(set)
    // [1, 2, 3]
    
    //可以传第二个参数,类似于数组的map方法,对里边对每一项进行处理
    console.log(Array.from(set, item => item + 1))
    // [2, 3, 4]
    
  • 字符串转换为数组

  • const str = Array.from('abbcd')
    // ["a", "b", "b", "c", "d"]
    
  • Array.from的第二个参数:函数,类似于数组的map()方法

  • Array.from([1, 2, 3, 4], x => x * x)
    // [1, 4, 9, 16]
    
    //等同于
    Array.from(arrayLike).map(x => x * x)
    
    Array.from({length: 3}, x => 'jack')
    

results matching ""

    No results matching ""