试一试
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 |
浏览器兼容性
加载中…