You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何向已有数组添加新数组并返回新数组?

实现方法

你要实现的是将新数组作为单个子元素追加到已有二维数组的末尾,有两种常用写法,分别对应修改原数组、不修改原数组的场景:

  • 直接修改原数组:用push方法,这是最简便的写法
const existingArr = [[1,2,3], [4,5,6]]
const newArr = [7,8,9]
existingArr.push(newArr)
// 操作后existingArr的值为[[1,2,3],[4,5,6],[7,8,9]]
  • 不修改原数组、返回全新数组:这就是你要找的扩展运算符(spread operator)正确写法
const existingArr = [[1,2,3], [4,5,6]]
const newArr = [7,8,9]
const result = [...existingArr, newArr]
// result的值为[[1,2,3],[4,5,6],[7,8,9]],原existingArr不会被改动

常见错误原因

你之前用扩展运算符没得到正确结果,大概率是错误展开了待添加的新数组:如果写为[...existingArr, ...newArr],会把[7,8,9]的每个元素拆出来单独追加到外层,最终得到[[1,2,3],[4,5,6],7,8,9],不符合预期。因为你的需求是把整个新数组作为一个元素存入外层数组,不需要展开这个新数组本身。

内容的提问来源于stack exchange,提问作者Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:54:25