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

JS如何从数组中删除指定对象(如name为test3的元素)

删除JavaScript数组指定索引元素的几种方法

嘿,这个需求太常见了,我给你几个实用的实现方式,你可以根据自己的场景选:

1. 直接修改原数组:用splice()方法

这是最直接的方式,splice()可以直接在原数组上删除指定位置的元素。它的第一个参数是起始索引,第二个参数是要删除的元素个数。

代码示例:

var item = [ 
  {name:'test1',variable:20}, 
  {name:'test2',variable:20}, 
  {name:'test3',variable:20}, 
  {name:'test4',variable:20}, 
  {name:'test5',variable:20}, 
  {name:'test6',variable:20}, 
  {name:'test7',variable:20}, 
  {name:'test8',variable:20}
];

// 删除索引为2的元素(也就是test3)
item.splice(2, 1);

console.log(item); // 输出的数组里已经没有test3对应的对象了

注意:这个方法会直接改变原数组,如果你的原数组还需要保留,就别用这个。

2. 保留原数组:用filter()方法

如果不想改动原数组,想要生成一个新的数组,filter()就很合适。我们可以通过判断索引来排除目标元素:

代码示例:

var item = [ 
  {name:'test1',variable:20}, 
  {name:'test2',variable:20}, 
  {name:'test3',variable:20}, 
  {name:'test4',variable:20}, 
  {name:'test5',variable:20}, 
  {name:'test6',variable:20}, 
  {name:'test7',variable:20}, 
  {name:'test8',variable:20}
];

// 生成新数组,排除索引为2的元素
var newItem = item.filter((_, index) => index !== 2);

console.log(newItem); // 新数组不含test3
console.log(item); // 原数组完全没变化

额外补充:根据name属性删除(如果索引不确定)

要是你有时候不确定索引,但知道要删的对象name是test3,也可以用filter()直接匹配属性:

var newItem = item.filter(obj => obj.name !== 'test3');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:19:16