[英]Why splice method does not work and delete item on array in TypeScript
I have an array type Person that has some data.我有一个包含一些数据的数组类型 Person。 Example:例子:
const people = [{name: "John", age: "18"},{name: "Mike", content: "20"},{label: "Brand", content: "18"},{label: "Alice", content: "50"},{label: "Zina", content: "10"}];
I have another array type of string[] that has the following data: names=["John", "Zina"]
;我有另一种 string[] 数组类型,它具有以下数据: names=["John", "Zina"]
;
I try to delete the names that are on the second array from the first array like this:我尝试从第一个数组中删除第二个数组上的名称,如下所示:
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);
}
}
}
Why it does not work?为什么它不起作用?
If you like to keep the object reference from people
, you could iterate people
from the end, because Array#splice
with items to delete changes the indices of the following items.如果您想保留来自people
的对象引用,您可以从最后迭代people
,因为Array#splice
with items to delete 会更改以下项目的索引。
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; }
The splice
method is modifying the array inplace . splice
方法是在原地修改数组。 I suggest you to use filter
method.我建议你使用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)));
Please refer below Code.请参考以下代码。
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)
Splice is modifying the original array. Splice 正在修改原始数组。 ie on each iteration if condition return true, people array at that index gets replaced with undefined and hence gets error.即在每次迭代中,如果条件返回 true,则该索引处的 people 数组将被替换为 undefined,因此会出现错误。
you can use slice method to get data that you want to delete.您可以使用 slice 方法来获取要删除的数据。
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),);
}
}
}
or you can simply filter data using Filter method.或者您可以简单地使用 Filter 方法过滤数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.