javascript - 如何从 Javascript 数组中删除元素?
问题描述
我想在迭代中使用带有 if 条件的 splice 方法删除数组中的某些元素。我执行以下操作:
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:"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);
推荐阅读
- r - 使用列表中的变量名称来命名 R 中的列表条目
- x509 - 如何使用基于 node-opcua 的客户端连接到需要基于证书的用户身份验证的 OPC-UA 服务器
- c# - Blazor Wasm(无 WebApi)Google 表格授权
- python - Scapy:发现已知源 ip 时发出警报
- typeorm - 如何在 typeorm 中使用存储库?
- css - 将 SmartTable 的选定行设为自定义颜色
- docker - GCP - 无法写回 UDP 数据包
- javascript - 给出了一个整数数组。检查它是否包含相同的元素
- c# - IssuerSigningKeys 更改时如何重置 OpenIdConnectConfiguration?
- python - 保存到/从 SQL 加载的大型稀疏矩阵数据与 Numpy 文件数据