Array.from()
是 JavaScript 中用于將類數組對象(array-like)或可迭代對象(iterable)轉換為真實數組的一個非常有用的方法。
📌 一、基本語法
Array.from(arrayLike, mapFn?, thisArg?)
參數說明:
參數 | 類型 | 描述 |
---|---|---|
arrayLike | 對象 | 一個類數組對象或可迭代對象(如字符串、Map、Set、DOM NodeList 等) |
mapFn | 函數(可選) | 類似于 map() 的回調函數,用于對每個元素進行處理 |
thisArg | 任意值(可選) | 執行 mapFn 時使用的 this 值 |
? 二、作用詳解
1. 把類數組對象轉成數組
類數組對象:有
length
屬性,并可以通過索引訪問元素,但沒有數組的方法(如push
,slice
等)
示例:
const arrayLike = {0: 'a',1: 'b',2: 'c',length: 3
};const arr = Array.from(arrayLike);
console.log(arr); // ['a', 'b', 'c']
2. 把字符串轉成字符數組
Array.from('hello');
// 輸出: ['h', 'e', 'l', 'l', 'o']
相比
str.split('')
,Array.from()
更適合處理帶 Unicode 字符的字符串。
3. 把 Set / Map 轉成數組
const set = new Set([1, 2, 3]);
Array.from(set); // [1, 2, 3]const map = new Map([['a', 1], ['b', 2]]);
Array.from(map); // [['a', 1], ['b', 2]]
4. 把 arguments 對象轉成數組(ES5 中常用)
function example() {return Array.from(arguments);
}
example(1, 2, 3); // [1, 2, 3]
5. 結合 DOM NodeList 使用
const divs = document.querySelectorAll('div');
const divArray = Array.from(divs);
divArray.forEach(div => console.log(div));
🔁 三、使用 mapFn
映射處理
你可以在創建數組的同時,對每個元素進行映射處理,相當于:
Array.from(obj, x => fn(x))
示例:
Array.from({ length: 5 }, (_, i) => i * 2);
// 輸出: [0, 2, 4, 6, 8]
這個用法非常適合用來生成數字序列、初始化數組等場景。
🧪 四、實用技巧示例
1. 生成指定長度的數字數組(從0開始)
Array.from({ length: 5 }, (_, i) => i);
// [0, 1, 2, 3, 4]
2. 生成隨機數數組
Array.from({ length: 5 }, () => Math.floor(Math.random() * 100));
// 示例輸出: [23, 78, 11, 45, 90]
3. 去重并轉成數組
const str = 'abacdef';
Array.from(new Set(str)); // ['a', 'b', 'c', 'd', 'e', 'f']
🆚 五、與 Array.prototype.slice.call()
的區別
在 ES5 中我們經常這樣把類數組轉成數組:
Array.prototype.slice.call(arrayLike);
但在 ES6 中,推薦使用更簡潔、語義更強的:
Array.from(arrayLike);
📝 總結
特性 | Array.from() |
---|---|
輸入類型 | 類數組、可迭代對象 |
是否改變原數組 | ? 不會修改原數組 |
是否返回新數組 | ? 返回一個新的數組 |
支持 .map() 式處理 | ? 支持 mapFn 回調 |
兼容性 | ? 大多數現代瀏覽器都支持(IE 不支持) |