【问题标题】:How to remove elements from a Javascript array? [duplicate]如何从 Javascript 数组中删除元素? [复制]
【发布时间】:2020-02-12 21:45:38
【问题描述】:

我想在迭代中使用带有 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 == '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”的两个元素,但只删除第一个元素。

【问题讨论】:

  • 您的方法无效,因为当您到达第二次服务时,索引:3 不再存在于您的数组中,因为在您第一次拼接后,您的数组长度变为 3,因此最后一个索引为 2。

标签: javascript


【解决方案1】:

您可以使用Array.prototype.filter()

代码:

const list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}];

const resultList = list.filter(item => item.type !== 'service');

console.log(resultList);

【讨论】:

  • 你不应该把它选为骗子吗?
  • 感谢您的快速回复。问题解决了。
【解决方案2】:

当使用forEach()If the array is modified during iteration, other elements might be skipped

为什么不用Array.prototype.filter()

filter() 方法创建一个新数组,其中包含所有通过所提供函数实现的测试的元素。

var list = [{type:"product",name:"Product A"},{type:"product",name:"Product B"},{type:"service", name:"Service A"},{type:"service", name:"Service B"}]

list = list.filter( item => item.type != 'service');
console.log(list);

【讨论】:

  • 你不应该把它选为骗子吗?
猜你喜欢
  • 1970-01-01
  • 2022-08-11
  • 1970-01-01
  • 2022-12-26
  • 2011-01-01
  • 2015-10-28
  • 2020-08-24
  • 2020-08-16
  • 2019-03-23
相关资源
最近更新 更多