es6 -- Array.from()函式的用法
阿新 • • 發佈:2018-12-09
前言
ES6為Array增加了from函式用來將其他物件轉換成陣列。
當然,其他物件也是有要求,也不是所有的,可以將兩種物件轉換成陣列。
1.部署了Iterator(迭代器)介面的物件,比如:Set,Map,Array。
2.類陣列物件,什麼叫類陣列物件,就是一個物件必須有length屬性,沒有length,轉出來的就是空陣列。
具體用法
Array.from可以接受三個引數
我們看定義:Array.from(arrayLike [, mapFn [, thisArg]])
arrayLike:被轉換的的物件。 mapFn:map函式。 thisArg:map函式中this指向的物件。
第一個引數
在這裡很好理解,就是要被轉換的物件
第二個引數,map函式
用來對轉換中的每一個元素進行加工,並將加工後的結果作為結果陣列的元素值。
console.log(Array.from([1, 2, 3, 4, 5], (n) => n + 1))
// 結果[2,3,4,5,6] map函式的實際的做用是給每個元素都加了1
第三個引數,map函式中this指向的物件
該引數是非常有用的,我們可以將被處理的資料和處理物件分離,將各種不同的處理資料的方法封裝到不同的的物件中去,處理方法採用相同的名字。
在呼叫Array.from對資料物件進行轉換時,可以將不同的處理物件按實際情況進行注入,以得到不同的結果,適合解耦。
這種做法是模板設計模式的應用,有點類似於依賴注入。
const obj = {
add: function (n) {
return n + 1;
}
}
console.log( Array.from(
[1, 2, 3, 4, 5],
function (x){
return this.add(x)
},
obj))
//結果 [2,3,4,5,6]
轉換set物件
const setArr = new Set();
setArr.add(1).add(2).add("www");
console.log (Array.from(setArr));
// 結果 [1, 2, "www"]
const setArr1 = new Set([1,1,12,2,3,4,5,5,6,6]);
console.log(Array.from(setArr1));
// 或者使用展開表示式 console.log([...setArr1]);
// 結果 [1, 12, 2, 3, 4, 5, 6]
// 同時不難發現set具有去重的功能
轉換map物件
const mapArr = new Map();
mapArr.set('m1', 1);
mapArr.set('m2', 2);
mapArr.set('m3', 3);
console.log(Array.from(mapArr));
// 結果 [['m1', 1],['m2', 2],['m3', 3]]
console.log(Array.from(mapArr)[1]);
// 結果 ["m2", 2]
轉換類陣列物件
一個類陣列物件必須要有length屬性,他們的元素屬性名必須是數值或者可以轉換成數值的字元。
注意:
- 屬性名代表了陣列的索引號,如果沒有這個索引號,轉出來的陣列中對應的元素就為length長度個undefined。
- 如果沒有length屬性,轉換出來的陣列也是空的;
帶length
//注意看區別
console.log(Array.from({
0: 'dd',
1: 'gg',
2: 'w3',
length:3
}))
// 結果 ["dd", "gg", "w3"]
console.log(Array.from({
0: 'dd',
1: 'gg',
4: 'w3',
length:3
}))
// 結果 ["dd", "gg", undefined]
console.log(Array.from({
"0": 'dd',
1: 'gg',
"3": 'w3',
length:6
}))
// 結果 ["dd", "gg", undefined, "w3", undefined, undefined]
//總結,生成陣列的長度由length屬性確定,如果相應索引位置上沒有值,則為undefined
不帶length
console.log( Array.from({
0: 3,
1: 12
}))
// 結果 []
物件的屬性名不能轉換成索引號時
console.log(Array.from({
"s": 'dd',
"ss": 'gg',
"n": 'w3',
length:3
}))
// 結果 [undefined, undefined, undefined]
如果您對我的部落格內容有疑惑或質疑的地方,請在下方評論區留言,或郵件給我,共同學習進步。