Nic*_*ick 4 javascript underscore.js
在我的游戏中,我需要找到一个包含在"单位"数组中的怪物.此数组位于世界对象内的空间单元结构内.如何在不编写丑陋代码的情况下找到此单元?
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;
Run Code Online (Sandbox Code Playgroud)
这里的麻烦是当我找到正确的值时我不能使用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': []
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
退房_.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;
Run Code Online (Sandbox Code Playgroud)
请注意,_.some如果对象为null,则为no-ops,因此无需检查该对象.
| 归档时间: |
|
| 查看次数: |
6495 次 |
| 最近记录: |