試一試
console.log(Array.from("foo"));
// Expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]
語法
Array.from(items)
Array.from(items, mapFn)
Array.from(items, mapFn, thisArg)
引數
items-
要轉換為陣列的 iterable 或 array-like 物件。
mapFn可選-
一個將在陣列的每個元素上呼叫的函式。如果提供了此引數,則新增到陣列的每個值都將首先透過此函式進行處理,並將
mapFn的返回值新增到陣列中。該函式將使用以下引數進行呼叫 thisArg可選-
執行
mapFn時用作this的值。
返回值
一個新的 Array 例項。
描述
Array.from() 允許你從以下物件建立 Array:
- iterable 物件(例如
Map和Set);或者,如果物件不是 iterable,則從 - array-like 物件(具有
length屬性和索引元素的 ]];
要將普通的、非 iterable 或非 array-like 物件轉換為陣列(透過列舉其屬性鍵、值或兩者),請使用 Object.keys()、Object.values() 或 Object.entries()。要將 async iterable 轉換為陣列,請使用 Array.fromAsync()。
Array.from() 永遠不會建立稀疏陣列。如果 items 物件缺少某些索引屬性,它們將在新陣列中變為 undefined。
Array.from() 有一個可選引數 mapFn,它允許你對正在建立的陣列的每個元素執行一個函式,類似於 map()。更清晰地說,Array.from(obj, mapFn, thisArg) 的結果與 Array.from(obj).map(mapFn, thisArg) 相同,不同之處在於它不建立中間陣列,並且 mapFn 只接收兩個引數(element、index),而不接收整個陣列,因為陣列仍在構建中。
注意:此行為對於 typed arrays 更重要,因為中間陣列的值將被截斷以適應適當的型別。Array.from() 的實現與 TypedArray.from() 具有相同的簽名。
Array.from() 方法是一個通用工廠方法。例如,如果 Array 的子類繼承了 from() 方法,則繼承的 from() 方法將返回子類的例項,而不是 Array 例項。實際上,this 值可以是任何接受單個引數(表示新陣列長度)的建構函式。當 items 作為 iterable 傳遞時,建構函式將不帶引數呼叫;當 array-like 物件被傳遞時,建構函式將使用 array-like 物件的 規範化長度 呼叫。最終的 length 將在迭代完成後再次設定。如果 this 值不是建構函式,則將使用普通的 Array 建構函式。
示例
從字串建立陣列
Array.from("foo");
// [ "f", "o", "o" ]
從 Set 建立陣列
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]
從 Map 建立陣列
const map = new Map([
[1, 2],
[2, 4],
[4, 8],
]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([
["1", "a"],
["2", "b"],
]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
從 NodeList 建立陣列
// Create an array based on a property of DOM Elements
const images = document.querySelectorAll("img");
const sources = Array.from(images, (image) => image.src);
const insecureSources = sources.filter((link) => link.startsWith("http://"));
從類陣列物件(arguments)建立陣列
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
使用箭頭函式和 Array.from()
// Using an arrow function as the map function to
// manipulate the elements
Array.from([1, 2, 3], (x) => x + x);
// [2, 4, 6]
// Generate a sequence of numbers
// Since the array is initialized with `undefined` on each position,
// the value of `v` below will be `undefined`
Array.from({ length: 5 }, (v, i) => i);
// [0, 1, 2, 3, 4]
序列生成器(範圍)
// Sequence generator function (commonly referred to as "range", cf. Python, Clojure, etc.)
const range = (start, stop, step) =>
Array.from(
{ length: Math.ceil((stop - start) / step) },
(_, i) => start + i * step,
);
// Generate a sequence of numbers from 0 (inclusive) to 5 (exclusive), incrementing by 1
range(0, 5, 1);
// [0, 1, 2, 3, 4]
// Generate a sequence of numbers from 1 (inclusive) to 10 (exclusive), incrementing by 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
// Generate the Latin alphabet making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0) + 1, 1).map((x) =>
String.fromCharCode(x),
);
// ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
在非陣列建構函式上呼叫 from()
from() 方法可以在任何接受單個引數(表示新陣列長度)的建構函式上呼叫。
function NotArray(len) {
console.log("NotArray called with length", len);
}
// Iterable
console.log(Array.from.call(NotArray, new Set(["foo", "bar", "baz"])));
// NotArray called with length undefined
// NotArray { '0': 'foo', '1': 'bar', '2': 'baz', length: 3 }
// Array-like
console.log(Array.from.call(NotArray, { length: 1, 0: "foo" }));
// NotArray called with length 1
// NotArray { '0': 'foo', length: 1 }
當 this 值不是建構函式時,將返回一個普通的 Array 物件。
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-array.from |
瀏覽器相容性
載入中…