Array From Builds Sequences With Map Fn

Array.from with a length shell and a map fn builds numeric sequences, expands strings by code points, and converts iterables with a transform.

JavascriptData Integrity

Code

javascriptsnippet
14 lines
// Array.from({length}) 先造出稀疏壳,第二个参数 mapFn 逐位填值
const steps = Array.from({ length: 5 }, (_, i) => (i + 1) * 10);
console.log('steps:', steps);

// 从字符串按码点展开:emoji 代理对保持完整,不会被拆成两个元素
const glyphs = Array.from('a😀b');
console.log('glyphs:', glyphs, 'length:', glyphs.length);

// 对照:按 UTF-16 码元切分会把 😀 撕成两个孤立代理项
console.log('code units:', 'a😀b'.split(''), 'length:', 'a😀b'.split('').length);

// 从 Set 等可迭代对象转换,mapFn 顺手加工每个元素
const squares = Array.from(new Set([3, 1, 3, 2]), (n) => n * n);
console.log('squares:', squares);

Output

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

steps: [ 10, 20, 30, 40, 50 ]
glyphs: [ 'a', '😀', 'b' ] length: 3
code units: [ 'a', '\ud83d', '\ude00', 'b' ] length: 4
squares: [ 9, 1, 4 ]

How it works

Array.from({ length: 5 }, (_, i) => (i + 1) * 10) fills the holey shell in one call: Array.from reads the numeric length, allocates exactly that many slots, and invokes the map function once per index, so the array of undefined holes never has to be looped over by hand. When the source is a string, Array.from iterates Unicode code points instead of UTF-16 code units, which is why 'a😀b' yields three elements with the emoji’s surrogate pair intact — the contrast line shows split('') tearing the same emoji into two lone surrogates and reporting length 4. The last statement converts a Set to an array while the second argument squares each element during the copy, so deduplicate-then-transform runs without an intermediate loop.

What deserves a second look

  • No package manager involved — every call resolves to a built-in API.

One line does most of the work here:

const squares = Array.from(new Set([3, 1, 3, 2]), (n) => n * n);

Right behind it in importance:

const steps = Array.from({ length: 5 }, (_, i) => (i + 1) * 10);

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API.