我需要在数组中有一个对象的索引,这样我就可以删除数组的这一部分。我尝试使用这个:
var index = this.urenRegistratie.indexOf(newDatum);
但它一直返回-1,我不知道为什么会这样。
这是我拥有的代码的一部分。它从 html 中的表单中获取数据并将其放入我的数组中,现在我已经准备好一个 if 语句(exisitingDatum),我的代码需要在那里。有人可以帮帮我吗?
store(newValue:number, newDatum, newAanwezig, newComment){
const existingDatum = this.urenRegistratie.find(billable => {
return billable.datum === newDatum;
return
});
if (!existingDatum) {
let billable = new BillableHours();
billable.datum = newDatum;
billable.hours = +newValue;
billable.aanwezig = newAanwezig;
billable.comment = newComment;
if(billable.aanwezig == "Aanwezig" && billable.hours !== 0 && billable.datum !== null) {
this.urenRegistratie.push(billable);
}
}
if(existingDatum) {
}
}
最佳答案
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.
如果您有这样的对象数组,请尝试使用
findIndex
:const a = [
{ firstName: "Adam", LastName: "Howard" },
{ firstName: "Ben", LastName: "Skeet" },
{ firstName: "Joseph", LastName: "Skeet" }
];
let index = a.findIndex(x => x.LastName === "Skeet");
console.log(index);
关于javascript - 如何使用 Angular 获取数组中对象的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58971067/