在我的游戏中,我需要找到包含在“单位”数组中的特定怪物。该数组位于世界对象内的空间单元结构内。如何在不编写丑陋代码的情况下找到这个单元?
var foundUnit = null;
_.each(worldHandler.world, function(zone) {
if ( foundUnit ) return;
_.each(zone, function(cellX) {
if ( foundUnit ) return;
_.each(cellX, function(cellY) {
if ( foundUnit ) return;
if ( !_.isUndefined(cellY.units) ) {
_.each(cellY.units, function(unit) {
if ( foundUnit ) return;
if ( unit.id === id ) foundUnit = unit;
});
}
});
});
});
return foundUnit;
这里的麻烦是当我找到正确的值时我不能使用return。 Return 内部 _.each() 将继续当前循环。是否有更好/更简洁的方法来查找嵌套对象中的特定值?
示例数据:
{ // World
'1': { // Zone
'-1': { // Cell X
'-1': { // Cell Y
'units': []
},
'0': {
'units': [{id:5}]
},
'1': {
'units': []
}
}
} {
'0': {
'-1': {
'units': []
},
'0': {
'units': []
},
'1': {
'units': []
}
}
} {
'1': {
'-1': {
'units': []
},
'0': {
'units': []
},
'1': {
'units': []
}
}
}
}
最佳答案
查看_.some
。
var foundUnit = null;
_.some(worldHandler.world, function(zone) {
return _.some(zone, function(cellX) {
return _.some(cellX, function(cellY) {
return _.some(cellY.units, function(unit) {
if ( unit.id === id ) {foundUnit = unit; return true; }
});
});
});
});
return foundUnit;
请注意,如果对象为 null,_.some
不会执行任何操作,因此无需检查。
关于javascript - 如何使用下划线的每个函数在嵌套对象中有效地找到一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17008218/