javascript - 如何使用 Angular 获取数组中对象的索引?

标签 javascript arrays angular typescript indexof

我需要在数组中有一个对象的索引,这样我就可以删除数组的这一部分。我尝试使用这个:

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

    }

  }

最佳答案

As mdn says:

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/

相关文章:

javascript - Angular 4 : How do I build a dynamic list of checkboxes to submit in a form?

javascript - 如何使用从服务器接收到的秒数显示用户的 “last seen at” 时间

javascript - 状态未初始化为初始状态

javascript - 在 Chrome 中打开 url 并关闭 Safari 选项卡

C++ 需要从数组中删除某些值

python - 从数组末尾取消填充全零行

javascript - 如何从对象数组中读取属性值?

javascript - 如何将 JQuery 日期选择器的格式更改为 MM/DD/YYYY

javascript - 我可以将 JavaScript JSON.parse 与外部数组一起使用吗?

Angular 8 数字输入最小值/最大值