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

如何在JavaScript数组最后一项前插入JSON元素并去除额外嵌套数组

问题原因

你当前的代码存在两个问题:

  1. 插入索引参数错误:array.slice(-1)返回的是包含数组最后一项的子数组,不是数字类型的索引值,插入到倒数第一项之前的正确索引是array.length - 1
  2. 多元素插入未展开:原有insert函数会将传入的newItem整体作为单个数组成员插入,所以你传入的insertItems数组会被整体包裹成一项

修复方案

调整insert函数支持多元素插入,调用时传入正确的索引即可:

const array = [ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Index Value': 12 }      
]

// 调整函数参数,用剩余参数接收所有待插入元素
const insert = (arr, index, ...newItems) => [
    ...arr.slice(0, index),
    ...newItems, // 展开待插入元素,避免外层包裹数组
    ...arr.slice(index)
]

const insertItems= [{ 'Japan': { Score: "54", PlayedMatched: "56" } },{ 'Russia': { Score: "99", PlayedMatched: "178" } }];

// 传入正确的插入索引:数组长度-1 就是倒数第一项的位置,插入后新元素就在它前面
const result = insert(array, array.length - 1, ...insertItems)

console.log(result);

运行后输出就是你需要的效果:

[ 
  {India: { Score: '12', PlayedMatched: '21' } },
  { China: { Score: '52', PlayedMatched: '51' }},
  { USA: { Score: '15', PlayedMatched: '06' } },
  { 'Japan': { Score: "54", PlayedMatched: "56" } },
  { 'Russia': { Score: "99", PlayedMatched: "178" } },
  { 'Index Value': 12 }      
]

如果只需要实现插入到倒数第一项前,不想修改原有insert函数,也可以直接用数组原生的splice方法实现:

// splice参数说明:(插入位置, 删除元素数量, ...待插入元素)
array.splice(array.length - 1, 0, ...insertItems)

注意splice会修改原数组,如果你不希望修改原数组,可以先拷贝一份原数组再操作。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 22:42:02