Array.from()

Array.from() 静态方法从 iterablearray-like 对象创建一个新的浅复制 Array 实例。

¥The Array.from() static method creates a new, shallow-copied Array instance from an iterable or array-like object.

Try it

语法

¥Syntax

js
Array.from(arrayLike)
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)

参数

¥Parameters

arrayLike

要转换为数组的可迭代或类似数组的对象。

mapFn Optional

调用数组的每个元素的函数。如果提供,则首先将要添加到数组的每个值都通过此函数传递,然后将 mapFn 的返回值添加到数组中。使用以下参数调用该函数:

element

数组中当前正在处理的元素。

index

数组中当前正在处理的元素的索引。

thisArg Optional

执行 mapFn 时用作 this 的值。

返回值

¥Return value

一个新的 Array 实例。

¥A new Array instance.

描述

¥Description

Array.from() 允许你从以下位置创建 Array

¥Array.from() lets you create Arrays from:

  • 可迭代对象MapSet 等对象);或者,如果该对象不可迭代,
  • 类似数组的对象(具有 length 属性和索引元素的对象)。

要将不可迭代或不可类数组的普通对象转换为数组(通过枚举其属性键、值或两者),请使用 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 只接收两个参数(elementindex)而没有整个数组,因为该数组仍在构建中。

¥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 as TypedArray.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.

示例

¥Examples

来自字符串的数组

¥Array from a String

js
Array.from("foo");
// [ "f", "o", "o" ]

集合中的数组

¥Array from a Set

js
const set = new Set(["foo", "bar", "baz", "foo"]);
Array.from(set);
// [ "foo", "bar", "baz" ]

来自映射的数组

¥Array from a Map

js
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 中的数组

¥Array from a NodeList

js
// 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://"));

来自类数组对象的数组(参数)

¥Array from an Array-like object (arguments)

js
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [ 1, 2, 3 ]

使用箭头函数和 Array.from()

¥Using arrow functions and Array.from()

js
// 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)

js
// 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.

js
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.

js
console.log(Array.from.call({}, { length: 1, 0: "foo" })); // [ 'foo' ]

规范

Specification
ECMAScript Language Specification
# sec-array.from

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看