在嵌套对象中搜索值
Search for a value in nested objects
我必须检查对象是否包含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'));
注意:你不必比较childrenLeft
和undefined
。因为undefined
是假的,任何对象都是真,所以你可以在if
条件下求childrenLeft
的值。
相关文章:
- 以有效的方式搜索对象列表 mongo
- findAndModify,如何对文档进行操作's数组搜索对象并更改字段值
- Lodash搜索对象属性并修改值
- 如何使用糖.js来搜索对象中的数组
- Javascript使用.indexof搜索对象并创建一个表
- 搜索对象数组中的元素
- 如何在数组中搜索对象属性
- 在Javascript中搜索对象
- 基于NodeJS中的其他数组过滤/搜索对象的JavaScript数组
- 自定义mongodb搜索对象
- 根据属性名称递归搜索对象中的值
- 使用香草JavaScript搜索对象数组
- 如何做一个深度搜索对象从一个给定的字符串
- 在客户端搜索对象
- 在Javascript中搜索对象数组
- 如何用输入数组搜索对象
- Javascript -按键搜索对象
- 快速搜索对象数组以查找匹配的键/值对
- 在JavaScript中递归搜索对象
- 在对象数组中搜索对象javascript