← 中文资源

简体中文版本

Symbol.isConcatSpreadable 控制 concat 展开

concat 对数组类对象默认整体插入、对数组默认逐项展开;Symbol.isConcatSpreadable 可以双向翻转这两种行为,嵌套保持还是摊平由这个符号决定。

阅读英文原文

运行结果

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

[1,2,3,4]
[1,2,{"0":"a","1":"b","length":2}]
[1,2,"a","b"]
[1,2,[3,4]]

实现说明

各个操作都建立在顶层绑定之上: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)));