为什么拼接方法不起作用并在 TypeScript 中删除数组上的项目

Why splice method does not work and delete item on array in TypeScript

我有一个包含一些数据的数组类型 Person。示例:

const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{label: "Brand", content: "18"},{label: "Alice", content: "50"},{label: "Zina", content: "10"}];

我有另一种数组类型的字符串[],它有以下数据: names=["John", "Zina"];

我尝试从第一个数组中删除第二个数组中的名称,如下所示:

  for (let i = 0; i < people.length; i++) {
    for (let j = 0; j < names.length; j++) {
      if (names[j] === people[i].name) {
        people.splice(i);
      }
    }
  }

为什么不起作用?

splice 方法正在修改数组 inplace。我建议你使用 filter 方法。

const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{name: "Brand", content: "18"},{name: "Alice", content: "50"},{name: "Zina", content: "10"}], names=["John", "Zina"];


console.log(people.filter(({name}) => !names.includes(name)));

如果您想保留来自 people 的对象引用,您可以从末尾开始迭代 people,因为 Array#splice 与要删除的项目会更改以下项目的索引。

var people = [{ name: "Mike", content: "20" }, { label: "Brand", content: "18" }, { label: "Alice", content: "50" }, { label: "Zina", content: "10" }],
    names = ["John", "Zina"],
    i = people.length;

while (i--) {
    if (names.includes(people[i].name) || names.includes(people[i].label)) {
        people.splice(i, 1);
    }
}

console.log(people);
.as-console-wrapper { max-height: 100% !important; top: 0; }

请参考下面的代码。

const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{label: "Brand", content: "18"},{label: "Alice", content: "50"},{label: "Zina", content: "10"}];
const names = ["Mike","Shiv"];

for (let i = 0; i < people.length; i++) {
debugger
    for (let j = 0; j < names.length; j++) {
      if (names[j] === people[i].name) {
        people.splice(i,1);
      }
    }
  }
 console.log(people)

拼接正在修改原始数组。即 在每次迭代中,如果条件 return 为真,则该索引处的人员数组将被替换为未定义,因此会出错。

您可以使用切片方法来获取您要删除的数据。

 for (let i = 0; i < people.length; i++) {
    for (let j = 0; j < names.length; j++) {
      if (names[j] === people[i].name) {
     console.log("matched",names[j],people[i].name, people.slice(i,i+1),);
      }
    }
  }

或者您可以使用 Filter 方法简单地过滤数据。