← 中文资源

简体中文版本

concat 合并且不拍平

concat 返回新数组合并数组与散值:嵌套数组保持原样(要拍平用 flat),对象按引用与源共享,源数组不被改动;只拼两个数组时展开写法与它等价。

阅读英文原文

运行结果

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

merged: [ 'a1', 'a2', 'b1', 'b2', 'c1', 'c2', [ 'c3' ] ]
pageTwo intact: [ 'b1', 'b2' ]
shared row: 99
nested kept: [ 'c3' ]
spread same: a1,a2,b1,b2

实现说明

顶层就这几处状态:pageOne、pageTwo、merged、row。 顶层对象字面量把 id 定成普通值——没有派生,背后也没有导入。

使用要点

  • 跑完文件,输出里会留下标记——merged:、pageTwo intact:、shared row:。

常见问题

有需要管理的依赖吗?

没有。无需声明或安装任何依赖。 文件用顶层绑定保存自己的状态:pageOne、pageTwo、merged。

核心语句

const merged = pageOne.concat(pageTwo, 'c1', ['c2', ['c3']]);
const spread = [...pageOne, ...pageTwo];
const withRow = [].concat(row);

代码示例

// concat merges arrays and bare values into a new array; nested arrays are not flattened
const pageOne = ['a1', 'a2'];
const pageTwo = ['b1', 'b2'];
const merged = pageOne.concat(pageTwo, 'c1', ['c2', ['c3']]);
console.log('merged:', merged);
console.log('pageTwo intact:', pageTwo);

// shallow merge: objects are still shared by reference with the source
const row = { id: 1 };
const withRow = [].concat(row);
withRow[0].id = 99;
console.log('shared row:', row.id);

// nested arrays stay as-is; use flat when flattening is needed
console.log('nested kept:', merged[6]);

// spread syntax is equivalent to concat when joining two arrays
const spread = [...pageOne, ...pageTwo];
console.log('spread same:', spread.join(','));