ES6,Array.from()函數的用法

ES6爲Array增加了from函數用來將其他對象轉換成數組。

當然,其他對象也是有要求,也不是所有的,可以將兩種對象轉換成數組。

1.部署了Iterator接口的對象,比如:Set,Map,Array。

2.類數組對象,什麼叫類數組對象,就是一個對象必須有length屬性,沒有length,轉出來的就是空數組。

 

轉換map
將Map對象的鍵值對轉換成一個一維數組。
實際上轉換出來的數組元素的序列是key1,value1,key2,value2,key3,value3.....
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

將Set對象的元素轉換成一個數組。

const set1 = new Set();
set1.add(1).add(2).add(3)
console.log('%s', Array.from(set1))

結果

1,2,3

 

轉換字符串
可以吧ascii的字符串拆解成一個數據,也可以準確的將unicode字符串拆解成數組。
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
白,色,的,海

 

類數組對象
一個類數組對象必須要有length,他們的元素屬性名必須是數值或者可以轉換成數值的字符。
注意:屬性名代表了數組的索引號,如果沒有這個索引號,轉出來的數組中對應的元素就爲空。
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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章