严格评估的 JavaScript 替代方案
我正在制作一个 javascript 游戏,具有多个级别,存储在 json 中。 加载时,我运行一个函数来“解析”关卡对象,方法是替换默认值中不存在的值,或者用对象替换某些值,例如:
//i is the variable I use to loop through the enemies
if (typeof(level.enemies[i].life)=="undefined") {
level.enemies[i].life=100;
}
if (typeof(level.enemies[i].follow)=="number") {
level.enemies[i].follow=level.enemies[level.enemies[i].follow];
// replace the number of the enemy,
// by a reference to the actual enemy.
}
问题是我有很多类似的“if”对于整个函数中的这些,我想知道是否可以以某种方式将它们简化为一个函数,这样我就可以做到这一点:
replaceByType(level.enemies[i].life,"undefined",100);
replaceByType(level.enemies[i].follow,"number",level.enemies[level.enemies[i].follow]);
遗憾的是我不知道如何做到这一点,因为它们无法传递变量(除了对象之外) )通过参考。也许还有另一种方法可以简化我的代码?
I am making an javascript game, featuring several levels, stored in json.
When loading, I run a function to "parse" the level object by replacing values that are not present by their default values, or by replacing some values by objects, such as:
//i is the variable I use to loop through the enemies
if (typeof(level.enemies[i].life)=="undefined") {
level.enemies[i].life=100;
}
if (typeof(level.enemies[i].follow)=="number") {
level.enemies[i].follow=level.enemies[level.enemies[i].follow];
// replace the number of the enemy,
// by a reference to the actual enemy.
}
The problem is that I have a lot of "ifs" similar to these throughout the function, and I am wondering if I somehow can reduce them to a function so I can do this:
replaceByType(level.enemies[i].life,"undefined",100);
replaceByType(level.enemies[i].follow,"number",level.enemies[level.enemies[i].follow]);
Sadly I don't know how to do this, because their is no way to pass a variable(other than an object) by reference. Maybe there is another way to simplify my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想你想要这样的东西:
或者为什么不一次做多个属性:
你使用 jQuery 吗?如果是这样,你可以这样做:
I think you want something like this:
Or why not do multiple properties all at once:
Are you using jQuery? If so, you can just do this:
由于可以通过引用传递对象,因此可以传递要替换的对象的属性。
你几乎可以按照你想要的方式称呼它:
Since you can pass objects by reference, you can pass a property of the object that you want to replace.
Which you can call almost how you were wanting to:
这会将计算推迟到
replaceByType
内部。This defers evaluation until inside
replaceByType
.