我的数组类型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);
}
}
}
为什么不起作用?
拼接正在修改原始数组。即在每次迭代中,如果条件返回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方法过滤数据。
如果要保留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);
.as-console-wrapper { max-height: 100% !important; top: 0; }
方法正在修改数组inplace。我建议您使用splice
方法。
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)));