有没有更好的迭代和比较 2 个数组中的对象的方法?

Is there a nicer way of iteration and comparing objects in 2 arrays?

我对JS/Angular还很陌生,可能还有点不懂。我有 2 个数组:boardP1: BoardCellModel[][]forbiddenCells: BoardCellModel[]。我想知道,如果第一个数组中的单元格与第二个数组中的单元格匹配。在 C# 中有 LINQ 用于此。 JS中有类似的东西吗?现在我的代码如下所示:

private compareBoardWithForbiddenCells(
    forbiddenCells: Array<BoardCellModel>
  ): boolean {
    for (let i = 0; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        for (let f = 0; f < forbiddenCells.length; f++) {
          if (
            this.boardP1[i][j].col == forbiddenCells[f].col &&
            this.boardP1[i][j].row == forbiddenCells[f].row &&
            this.boardP1[i][j].value == 1
          ) {
            return false;
          }
        }
      }
    }

    return true;
  }

有没有更好的方法来编写这段代码?

您可以尝试下面的代码来实现您的目标,现在我有 2 个数组,names,lastNames,我将用标识符 (id) 匹配它们

let names = [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }, { id: 3, name: 'Oliver' }, { id: 4, name: 'Barry'}];
let lastNames = [{ id: 1, lastName: 'Doe'}, { id: 2, lastName: 'Abc'}, { id: 3, lastName: 'Queen'}, { id: 4, lastName: 'Allen' }]

names.forEach(item => item.lastName = lastNames.find(lname => item.id === lname.id).lastName);

console.log(names);

检查工作 code here

你可以对所有禁止的坐标取一个Set并提前检查值。

const
    forbidden = new Set,
    key = (...a) => a.join('|');

for (const { col, row } of forbiddenCells) forbidden.add(key(col, row));

for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
        if (this.boardP1[i][j].value !== 1) continue;
        if (forbidden.has(key(this.boardP1[i][j].col, this.boardP1[i][j].row))) return false;
    }
}
return true;