Array.from Adapts Array-Likes And Iterables

Array.from converts array-likes, iterables, and strings, and its mapFn argument builds transformed arrays in one pass without intermediate copies.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
// 类数组(length + 索引)转真数组:Array.from 按位读取
const arrayLike = { 0: 'a', 1: 'b', 2: 'c', length: 3 };
console.log('array-like:', Array.from(arrayLike));

// 第二个参数 mapFn 边遍历边构造,省掉中间数组
const squares = Array.from({ length: 5 }, (_, i) => i * i);
console.log('squares:', squares);

// 可迭代对象同样适用:Set 去重、Map 拆回键值对
console.log('set:', Array.from(new Set([1, 2, 2, 3])));
console.log('map pairs:', Array.from(new Map([['a', 1], ['b', 2]])));

// 字符串按码点迭代:emoji 不会被拆成代理对
console.log('codepoints:', Array.from('a\u{1F44D}b').length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

array-like: [ 'a', 'b', 'c' ]
squares: [ 0, 1, 4, 9, 16 ]
set: [ 1, 2, 3 ]
map pairs: [ [ 'a', 1 ], [ 'b', 2 ] ]
codepoints: 3

How it works

Top-level bindings arrayLike, squares hold the demo state — nothing sits inside a function scope.

The top-level object literal pins length as plain values — no derivation, no imports behind them.

What to watch for

  • It is dependency-free in the strict sense — the import list, if any, is empty of packages.

Putting it to use

The run leaves a labeled trail: array-like:, squares:, set:.

Core lines

const squares = Array.from({ length: 5 }, (_, i) => i * i);

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `arrayLike`, `squares`.