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.
Code
// 类数组(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: 3How 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
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Number to WordsConvert an integer up to 999,999,999,999 into US English words, using the short scale and a minus prefix for negative values.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.