Array.from()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2016.
Array.from()
静态方法从 iterable 或 array-like 对象创建一个新的浅复制 Array
实例。
¥The Array.from()
static method creates a new, shallow-copied Array
instance from an iterable or array-like object.
Try it
语法
参数
返回值
描述
¥Description
Array.from()
允许你从以下位置创建 Array
:
¥Array.from()
lets you create Array
s from:
要将不可迭代或不可类数组的普通对象转换为数组(通过枚举其属性键、值或两者),请使用 Object.keys()
、Object.values()
或 Object.entries()
。要将 异步可迭代 转换为数组,请使用 Array.fromAsync()
。
¥To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both), use Object.keys()
, Object.values()
, or Object.entries()
. To convert an async iterable to an array, use Array.fromAsync()
.
Array.from()
从不创建稀疏数组。如果 arrayLike
对象缺少某些索引属性,它们在新数组中将变为 undefined
。
¥Array.from()
never creates a sparse array. If the arrayLike
object is missing some index properties, they become undefined
in the new array.
Array.from()
有一个可选参数 mapFn
,它允许你对正在创建的数组的每个元素执行函数,类似于 map()
。更清楚地说,Array.from(obj, mapFn, thisArg)
与 Array.from(obj).map(mapFn, thisArg)
的结果相同,只是它没有创建中间数组,而 mapFn
只接收两个参数(element
,index
)而没有整个数组,因为该数组仍在构建中。
¥Array.from()
has an optional parameter mapFn
, which allows you to execute a function on each element of the array being created, similar to map()
. More clearly, Array.from(obj, mapFn, thisArg)
has the same result as Array.from(obj).map(mapFn, thisArg)
, except that it does not create an intermediate array, and mapFn
only receives two arguments (element
, index
) without the whole array, because the array is still under construction.
注意:此行为对于 类型数组 更为重要,因为中间数组的值必须被截断以适合适当的类型。
Array.from()
被实现为具有与TypedArray.from()
相同的签名。¥Note: This behavior is more important for typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.
Array.from()
is implemented to have the same signature asTypedArray.from()
.
Array.from()
方法是通用工厂方法。例如,如果 Array
的子类继承了 from()
方法,则继承的 from()
方法将返回子类的新实例,而不是 Array
实例。事实上,this
值可以是任何接受表示新数组长度的单个参数的构造函数。当可迭代对象作为 arrayLike
传递时,将不带参数调用构造函数;当传递类数组对象时,将使用类数组对象的 标准化长度 调用构造函数。当迭代结束时,最终的 length
将被再次设置。如果 this
值不是构造函数,则使用普通的 Array
构造函数。
¥The Array.from()
method is a generic factory method. For example, if a subclass of Array
inherits the from()
method, the inherited from()
method will return new instances of the subclass instead of Array
instances. In fact, the this
value can be any constructor function that accepts a single argument representing the length of the new array. When an iterable is passed as arrayLike
, the constructor is called with no arguments; when an array-like object is passed, the constructor is called with the normalized length of the array-like object. The final length
will be set again when iteration finishes. If the this
value is not a constructor function, the plain Array
constructor is used instead.
示例
来自字符串的数组
集合中的数组
来自映射的数组
NodeList 中的数组
来自类数组对象的数组(参数)
使用箭头函数和 Array.from()
¥Using arrow functions and 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 (range)
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP, etc.)
const range = (start, stop, step) =>
Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step);
// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
// Generate the alphabet using Array.from making use of it being ordered as a sequence
range("A".charCodeAt(0), "Z".charCodeAt(0), 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()
¥Calling from() on non-array constructors
可以在任何接受表示新数组长度的单个参数的构造函数上调用 from()
方法。
¥The from()
method can be called on any constructor function that accepts a single argument representing the length of the new array.
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
对象。
¥When the this
value is not a constructor, a plain Array
object is returned.
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]
规范
Specification |
---|
ECMAScript Language Specification # sec-array.from |
浏览器兼容性
BCD tables only load in the browser