在嵌套对象中搜索值

Search for a value in nested objects

本文关键字:搜索 对象 嵌套      更新时间:2023-09-26

我必须检查对象是否包含javascript中的值,我不知道如何做到这一点。对象看起来像这样:

Match {
  player1: undefined,
  player2: undefined,
  childrenLeft: 
   Match {
     player1: 'John',
     player2: 'Mary',
     childrenLeft: undefined,
     childrenRight: undefined },
  childrenRight: 
   Match {
     player1: 'Michael',
     player2: 'James',
     childrenLeft: undefined,
     childrenRight: undefined }
  }

现在这是一场决赛和两场半决赛的比赛,但它可能会更大,这取决于玩家的数量,所以我需要遍历整个树。我有这个函数,它应该返回下一个对手,但它不工作,当我搜索的球员在childleft。所以,当我执行Match.nextOpponent(James)时,结果是'Michael',但是当我执行Match.nextOpponent(Mary)时,结果是'undefined'。

Match.prototype.nextOpponent = function (player) {
    if (this.player1 === player) return this.player2;
    if (this.player2 === player) return this.player1;
    if (!this.player2 && !this.player1 && this.childrenRight !== undefined) return this.childrenRight.nextOpponent(player);
    if (!this.player1 && !this.player2 && this.childrenLeft !== undefined) return this.childrenLeft.nextOpponent(player);
}

有人能帮忙吗?非常感谢

出现问题是因为您在最后两个if块中使用了return,即使递归调用的返回值是undefined。这意味着,如果第一个if条件为真,则不可能尝试第二个if条件。

所以要解决这个问题,使用下面的代码:

Match.prototype.nextOpponent = function (player) {
    if (this.player1 === player) return this.player2;
    if (this.player2 === player) return this.player1;
    var match;
    if (!this.player2 && !this.player1 && this.childrenRight) 
        match = this.childrenRight.nextOpponent(player);
    // maybe previous return value was undefined, then try the other side:
    if (!match && !this.player1 && !this.player2 && this.childrenLeft) 
        match = this.childrenLeft.nextOpponent(player);
    return match;
}

function Match(p1, p2) {
    this.player1 = p1;
    this.player2 = p2;
    this.childrenLeft = undefined;
    this.childrenRight = undefined;
}
Match.prototype.nextOpponent = function (player) {
    if (this.player1 === player) return this.player2;
    if (this.player2 === player) return this.player1;
    var match;
    if (!this.player2 && !this.player1 && this.childrenRight) 
        match = this.childrenRight.nextOpponent(player);
    if (!match && !this.player1 && !this.player2 && this.childrenLeft) 
        match = this.childrenLeft.nextOpponent(player);
    return match;
}
var root = new Match();
root.childrenLeft = new Match('John', 'Mary'); 
root.childrenRight = new Match('Michael', 'James'); 
console.log('James plays: ', root.nextOpponent('James'));
console.log('Mary plays: ', root.nextOpponent('Mary'));

注意:你不必比较childrenLeftundefined。因为undefined是假的,任何对象都是真,所以你可以在if条件下求childrenLeft的值。