在嵌套对象中搜索值

时间:2016-11-13 12:53:30

标签: javascript

我必须检查对象是否包含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 }
  }

现在这是一场有决赛和两场半决赛的比赛,但是根据球员的数量可能要大得多,所以我需要遍历所有的树。 我有这个功能,假设返回下一个对手但是当我在childrenLeft上搜索玩家时它不起作用。所以,当我执行Match.nextOpponent(James)时,我得到了迈克尔'因此,当我执行Match.nextOpponent(Mary)时,我得到了“未定义的”#。

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);
}

有人可以帮忙吗? 非常感谢你

1 个答案:

答案 0 :(得分:0)

问题出现的原因是最后两个return块中的if,即使递归调用的返回值为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是假的,任何对象都是真实的,您只需评估childrenLeft条件下的if