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

问题描述 投票:1回答:4

我的数组类型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);
      }
    }
  }

为什么不起作用?

javascript arrays typescript splice
4个回答
0
投票

拼接正在修改原始数组。即在每次迭代中,如果条件返回true,则该索引处的人员数组将被undefined替换,因此会出错。

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

 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方法过滤数据。


2
投票

如果要保留people中的对象引用,则可以从末尾迭代people,因为Array#splice中要删除的项目会更改以下项目的索引。

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);

1
投票

.as-console-wrapper { max-height: 100% !important; top: 0; }方法正在修改数组inplace。我建议您使用splice方法。

filter

0
投票

请参阅下面的代码。

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)));
© www.soinside.com 2019 - 2024. All rights reserved.