首页 > 解决方案 > 如何从 Array 对象中删除所有元素,除了使用 typescript 给定的 id

问题描述

我正在尝试从projectSetexcept 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"}
    ]

标签: javascripttypescript

解决方案


你需要

  • 使用===代替=(=是赋值运算符)

  • 不要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)


推荐阅读