← 中文资源

简体中文版本

Array.of 让单个数字保持为数组元素

Array.of(7) 得到 [7],new Array(7) 得到 7 个空槽;只有两个以上参数时 new Array 才当作元素列表,Array.of 还能用 call 借给其它构造函数当通用工厂。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

Grid定义了示例的行为。

使用要点

  • 跑完文件,输出里会留下标记——Array.from(、Array.of(。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。

核心语句

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

代码示例

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