Array.of Keeps One-Number Arguments As Elements

Array.of(7) builds a one-element array while new Array(7) reserves seven empty slots, and Array.of stays a generic factory when borrowed with call.

JavascriptData Integrity

Code

javascriptsnippet
20 lines
// Array.of 把参数收集成数组元素:单数字不会变成稀疏占位
console.log('Array.of(7)      :', JSON.stringify(Array.of(7)), 'length', Array.of(7).length);
console.log('new Array(7)     : length', new Array(7).length, 'first slot', new Array(7)[0]);
console.log('Array.of(1,2,3)  :', JSON.stringify(Array.of(1, 2, 3)));

// new Array(3, 4) 歧义:两个以上参数才当作元素列表
console.log('new Array(3, 4)  :', JSON.stringify(new Array(3, 4)));

// Array.from 适合 array-like 与 iterable:Array.of 只收集给定参数
console.log("Array.from('ab') :", JSON.stringify(Array.from('ab')));
console.log('Array.of("ab")   :', JSON.stringify(Array.of('ab')));

// Array.of 是通用工厂:this 决定返回什么构造,不要求一定是 Array
class Grid {
  constructor(items) {
    this.items = items;
  }
}
const g = Array.of.call(Grid, 2, 4);
console.log('Grid instance    :', g instanceof Grid, JSON.stringify(g.items));

Output

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

Array.of(7)      : [7] length 1
new Array(7)     : length 7 first slot undefined
Array.of(1,2,3)  : [1,2,3]
new Array(3, 4)  : [3,4]
Array.from('ab') : ["a","b"]
Array.of("ab")   : ["ab"]
Grid instance    : true 2

How it works

Count the class Grid as the entire surface area of Array.of Keeps One-Number Arguments As Elements.

Points of care

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Using it

Output lines are prefixed (Array.of(7) :, new Array(7) : length, Array.of(1,2,3) :), making each step’s effect easy to spot.

Key statements

const g = Array.of.call(Grid, 2, 4);
this.items = items;

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.