Js Array.from() 将类似数组对象转换成数组

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

广州品牌设计公司https://www.houdianzi.com PPT模板下载大全https://redbox.wode007.com

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]
posted @ 2020-12-07 14:46  浅笑·  阅读(1106)  评论(0编辑  收藏  举报