如何从Javascript数组中删除元素?
我想在迭代中使用带有if条件的拼接方法删除数组中的某些元素。我做了以下工作:如何从Javascript数组中删除元素?,javascript,Javascript,我想在迭代中使用带有if条件的拼接方法删除数组中的某些元素。我做了以下工作: var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}] list.forEach(function (item, index) { if (item.type ==
var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]
list.forEach(function (item, index) {
if (item.type == 'service'){
list.splice(index, 1)
}
}
//result: list = list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"}]
//expected: list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"}]
我希望类型为“service”的两个元素都将被删除,但仅删除第一个元素。您可以使用
代码:
const list=[{type:“产品”,name:“产品A”},{type:“产品”,name:“产品B”},{type:“服务”,name:“服务A”},{type:“服务”,name:“服务B”}];
const resultList=list.filter(item=>item.type!=='service');
console.log(结果列表)代码>使用forEach()时
为什么不使用:
filter()
方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素
var list=[{type:“产品”,name:“产品A”},{type:“产品”,name:“产品B”},{type:“服务”,name:“服务A”},{type:“服务”,name:“服务B”}]
list=list.filter(item=>item.type!='service');
控制台日志(列表)
你不应该投票给dupe吗?你不应该投票给dupe吗?谢谢你的快速回复。问题已解决。您的方法不起作用,因为当您到达第二个服务时,索引:3不再存在于阵列中,因为在第一次拼接后,阵列长度变为3,所以最后一个索引为2。