乐趣区

js数组-Arrayfrom-将类似数组对象转换成数组

Array.from()会把类似数组的对象转换成真实数组,对象需满足两个条件:

  1. 具有 length 属性,length 的值即为数组的长度
  2. 对象 key 要是数字,并会作为数组的下标
let obj = {
    '0': 'first',
    '1': 'second',
    '2': 'third',
    length: 3
}
let arr = Array.from(obj)
console.log(arr) //["first", "second", "third"]

//es5 实现
let arr2 = Array.prototype.slice.call(obj)
console.log(arr2) //["first", "second", "third"]

Array.from()同样会对可遍历的数据结构 (如 Set) 和字符串进行转换

Array.from('abc') // ["a", "b", "c"]

let arr = Array.from(new Set(['a','b','c']))
console.log(arr) // ["a", "b", "c"]

此方法可以快速实现数组的复制

let arr = ['a','b',{'c1':'hello','c2':'world'}]
let newArr = Array.from(new Set(arr))
console.log(newArr) //["a", "b", {c1: "hello", c2: "world"}]
console.log(newArr == arr) //false

// 扩展运算符同样可以实现
let newArr2 = [...arr]
console.log(newArr2) //["a", "b", {c1: "hello", c2: "world"}]
console.log(newArr2 == arr) //false

Array.from()可以接收第二个参数,类似数组 map 方法,返回处理后的结果

let arr = [1, 2, 3]
let newArr = Array.from(arr, item => item *2)
console.log(newArr) //[2, 4, 6]

比如快速生成数组,每项从 1 到 100

let arr = Array.from(new Array(100), (item, index) => {return index + 1})
console.log(arr) //[1, 2, 3,..., 100]
退出移动版