JavaScript數(shù)組方法Array.from()的用法

1. 基本語(yǔ)法

語(yǔ)法:Array.from(類數(shù)組[, 回調(diào)函數(shù)[, 參數(shù)]])
說明:

  • 類數(shù)組:轉(zhuǎn)換成數(shù)組的類似數(shù)組或可迭代的對(duì)象
  • 回調(diào)函數(shù):可選參數(shù),如果加了這個(gè)參數(shù),表示數(shù)組中的元素都要執(zhí)行這個(gè)回調(diào)函數(shù)
  • 參數(shù):可選,執(zhí)行回調(diào)函數(shù)時(shí)的this對(duì)象

2. 字符串轉(zhuǎn)數(shù)組

let a = Array.from(123456789);
let b = Array.from("123456789");
console.log(a);
console.log(b);

結(jié)果:
[]
["1", "2", "3", "4", "5", "6", "7", "8", "9"]

說明:不能將數(shù)值類型的元素直接轉(zhuǎn)換成數(shù)組,即使調(diào)用Array.from()方法,返回的結(jié)果也只是一個(gè)空數(shù)組

2. 將Map轉(zhuǎn)換成數(shù)組

let map = new Map([['1','2'],['5','6'],['9','10']])
let mnc = Array.from(map);
console.log(mnc);

結(jié)果:
[Array(2), Array(2), Array(2)]
0: (2) ["1", "2"]
1: (2) ["5", "6"]
2: (2) ["9", "10"]

3. 將Set轉(zhuǎn)換成數(shù)組

let set = new Set([1,3,1,3,2,4,5,6]);
let cbn = Array.from(set);
console.log(cbn);

結(jié)果:
[1, 3, 2, 4, 5, 6]

4. 將函數(shù)參數(shù)轉(zhuǎn)數(shù)組

function func(){
    return Array.from(arguments);
}

let params = func(11,22,33,44,55,66,77,88,99);
console.log(params);

結(jié)果:
[11, 22, 33, 44, 55, 66, 77, 88, 99]

5. 箭頭函數(shù)轉(zhuǎn)數(shù)組

let a = Array.from([11,22,33,44,55,66,77,88,99],w => w * w * w);
console.log(a);
let b = Array.from({length:50},(m,k) => k);
console.log(b);

結(jié)果:
[1331, 10648, 35937, 85184, 166375, 287496, 456533, 681472, 970299]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

6. 數(shù)組去重合并

function filterArr(){
    let array = [].concat.apply([], arguments);
    let set = new Set(array);
    return Array.from(set);
}

let a1 = [1,2,4,5,6,7,8,0,2,3,4,12,6,7,9];
let a2 = [4,57,8,2,1,2,34,56,89,45,21,3,4];
let a0 = filterArr(a1,a2);
let b0 = filterArr(a2,a1);
console.log(a0);
console.log(b0);

結(jié)果:
[1, 2, 4, 5, 6, 7, 8, 0, 3, 12, 9, 57, 34, 56, 89, 45, 21]
[4, 57, 8, 2, 1, 34, 56, 89, 45, 21, 3, 5, 6, 7, 0, 12, 9]
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容