实现说明
各个操作都建立在顶层绑定之上:head、arrayLike、spread、sealed。
模块级对象字面量,键名固定:length。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 状态都挂在模块顶层:head、arrayLike、spread。
核心语句
const spread = { ...arrayLike, [Symbol.isConcatSpreadable]: true };
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
sealed[Symbol.isConcatSpreadable] = false;
代码示例
const head = [1, 2];
// 数组默认展开,嵌套只浅一层
console.log(JSON.stringify(head.concat([3, 4])));
// 数组类对象默认整体当作一个元素插入
const arrayLike = { 0: 'a', 1: 'b', length: 2 };
console.log(JSON.stringify(head.concat(arrayLike)));
// 打开 isConcatSpreadable:array-like 被逐项展开
const spread = { ...arrayLike, [Symbol.isConcatSpreadable]: true };
console.log(JSON.stringify(head.concat(spread)));
// 关掉它:真数组也能强制保持嵌套
const sealed = [3, 4];
sealed[Symbol.isConcatSpreadable] = false;
console.log(JSON.stringify(head.concat(sealed)));