javascript - 如何从 Array 对象中删除所有元素,除了使用 typescript 给定的 id
问题描述
我正在尝试从projectSet
except when中删除所有元素id = myid
。我遇到splice()
但不确定如何使它在我的代码中工作。例如:
var myid = 2
var projectSet =
[
{id: 1, name: "P1", description: "D1"},
{id: 2, name: "P2", description: "D2"},
{id: 3, name: "P3", description: "D3"},
]
for(var i = 0; i < projectSet.length; i++){
if (projectSet[i].id = myid)
{
if (i > -1)
{
this.projectSet.splice(i,1); // This is not working as expected.
}
}
}
console.log(projectSet)
预期输出:
var projectSet =
[
{id: 2, name: "P2", description: "D2"}
]
解决方案
你需要
使用
===
代替=
(=
是赋值运算符)不要
splice
在遍历数组时,否则你会跳过下一个索引(例如,在索引 1 处拼接一个项目后,索引 2 处的内容将立即向下滑动到索引 1,但你将继续比较下一次迭代中的索引 2,跳过以前在索引 2 处的内容,现在在索引 1 处)
改为使用filter
。
var myid = 2
var projectSet =
[
{ id: 1, name: "P1", description: "D1" },
{ id: 2, name: "P2", description: "D2" },
{ id: 3, name: "P3", description: "D3" },
]
const filtered = projectSet.filter(obj => obj.id === myid);
console.log(filtered)
推荐阅读
- java - allowUnsafeRenegotiation 不使用 System.setProperty("allowUnsafeRenegotiation","true")
- google-api-explorer - Cloud Talent Solution API v3 - 项目 292824132082 暂时被列入黑名单
- character-encoding - 在经典 ASP 中显示像 €₼лв៛₡ 这样的特殊符号和像 ₱₴ 这样的货币
- android - 使用合并和包含标签时如何在 Java 中获取视图?
- arrays - 为数组中所有对象的属性设置相同值的最佳方法
- python - App Engine Python,标准环境,使用 time.sleep
- elasticsearch - 添加一个查询,检查字段中是否存在值
- c# - 有没有办法使用适用于 .NET 的 AWS SDK 将对象从 S3 存储桶下载到文件目标?
- aem - 如何将 Sling 模型导出为 JSON 并将其呈现给最终用户?
- hawtio - hawtio 控制台中真正令人困惑的问题 - 浏览队列显示错误消息