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"]

此方法能夠快速實現數組的複製es5

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方法,返回處理後的結果prototype

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

好比快速生成數組,每項從1到100code

let arr = Array.from(new Array(100), (item, index) => { return index + 1 })
console.log(arr) //[1, 2, 3,..., 100]
相關文章
相關標籤/搜索