实现说明
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));