.includes() 在对象的一部分

.includes() on part of an object

所以我有一个目标对象。我想看看里面是否有一个特定的目标。

我正在这样做:

for (let i = 0; i < this.goalsHome.length; i++) {
    console.log(this.goalsHome[i].includes(goal));
}

导致错误 include does not exists on type object。

但是如果我想检查一个特定对象怎么办 属性?假设我想检查目标的评论是否与对象中的目标评论之一相匹配。那应该是可能的吧?通过循环遍历它?

但是如果我在中间添加 .comment 它说类型对象上不存在注释。

您可能想检查数组中是否有对象的注释与目标注释匹配。如果这是你想做的,你可以做

this.goalsHome.filter(goalHome => goalHome.comment === goal.comment);

如果您想查找所有匹配的对象。 (参见 MDN Web Docs

如果您想知道是否存在单个匹配项,可以像这样使用 Array.prototype.some() 方法;

this.goalsHome.some(goalHome => goalHome.comment === goal.comment);

如果数组中至少有一个匹配项(参见 MDN Web Docs),则 return 为真。

我最终使用了 stringify。

let goalFound = false;
let goalsSide;

    if (side == 'home') {
        goalsSide = this.goalsHome;
    } else {
        goalsSide = this.goalsAway;
    }

for (let i = 0; i < goalsSide.length; i++) {
            let stringGoals = JSON.stringify(goalsSide[i]);
            let stringGoal = JSON.stringify(goal);

            if (stringGoals == stringGoal) {
                goalFound = true;
                break;
            }
        }

        if (goalFound != true) {
            this.addGoalToArray(goal, side);
        }