ES6爲Array增加了from函數用來將其他對象轉換成數組。
當然,其他對象也是有要求,也不是所有的,可以將兩種對象轉換成數組。
1.部署了Iterator接口的對象,比如:Set,Map,Array。
2.類數組對象,什麼叫類數組對象,就是一個對象必須有length屬性,沒有length,轉出來的就是空數組。
const map1 = new Map(); map1.set('k1', 1); map1.set('k2', 2); map1.set('k3', 3); console.log('%s', Array.from(map1))
結果:
k1,1,k2,2,k3,3
將Set對象的元素轉換成一個數組。
const set1 = new Set(); set1.add(1).add(2).add(3) console.log('%s', Array.from(set1))
結果
1,2,3
console.log('%s', Array.from('hello world'))
console.log('%s', Array.from('\u767d\u8272\u7684\u6d77'))
結果:
h,e,l,l,o, ,w,o,r,l,d
白,色,的,海
console.log('%s', Array.from({ 0: '0', 1: '1', 3: '3', length:4 }))
結果:
0,1,,3
如果對象不帶length屬性,那麼轉出來就是空數組。
console.log('%s', Array.from({ 0: 0, 1: 1 }))
結果就是空數組。
對象的屬性名不能轉換成索引號時。
console.log('%s', Array.from({ a: '1', b: '2', length:2 }))
結果也是空數組
Array.from可以接受三個參數
我們看定義:
Array.from(arrayLike[, mapFn[, thisArg]])
arrayLike:被轉換的的對象。
mapFn:map函數。
thisArg:map函數中this指向的對象。
第二個參數,map函數
用來對轉換中,每一個元素進行加工,並將加工後的結果作爲結果數組的元素值。
console.log('%s', Array.from([1, 2, 3, 4, 5], (n) => n + 1))
結果:
上面的map函數實際上是給數組中的每個數值加了1。
2,3,4,5,6
第三個參數,map函數中this指向的對象
該參數是非常有用的,我們可以將被處理的數據和處理對象分離,將各種不同的處理數據的方法封裝到不同的的對象中去,處理方法採用相同的名字。
在調用Array.from對數據對象進行轉換時,可以將不同的處理對象按實際情況進行注入,以得到不同的結果,適合解耦。
這種做法是模板設計模式的應用,有點類似於依賴注入。
let diObj = { handle: function(n){ return n + 2 } }
console.log('%s', Array.from( [1, 2, 3, 4, 5], function (x){ return this.handle(x) }, diObj))
結果:
3,4,5,6,7
End