好吧,这个标题听起来有点疯狂。我有一个对象,它是根据一堆输入(来自用户)构建的。我根据收到的值设置它们,但有时它们根本没有设置,这使得它们为空。我真正想做的是为《魔兽世界》制作一个元素生成器。这些项目可以具有多个属性,这些属性对于用户来说看起来都是相同的。这是我的例子:
+3 Agility
+5 Stamina
+10 Dodge
理论上,这应该只是获取对象的属性名称和键值,然后以相同的方式输出它。但是,如何设置该 if 语句?
这是我当前的 if 语句 MADNESS 的样子:
if(property == "agility") {
text = "+" + text + " Agility";
}
if(property == "stamina") {
text = "+" + text + " Stamina";
}
if(property == "dodge") {
text = "+" + text + " Dodge";
}
你明白这一点了吗?在《魔兽世界》中,有大量的属性,因此我必须为每个属性创建一个 if 语句,这很糟糕,因为属性太多了。它基本上是重复的,但仍然一直使用属性名称。这是我的 JSFiddle 的样子:http://jsfiddle.net/pm2328hx/这样你就可以自己玩了。谢谢!
编辑:哦,顺便说一句,我想做的是这样的:
if(property == "agility" || property == "stamina" || ....) {
text = "+" + text + " " + THE_ABOVE_VARIABLE_WHICH_IS_TRUE;
}
这也很hacky。我绝对不希望这样。
最佳答案
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property;
}
如果您需要将第一个字母大写:
if(['agility','stamina','dodge'].indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
每条评论更新:
如果您已经在某处拥有所有属性的数组,请使用该数组
var myatts = [
'agility',
'stamina',
'dodge'
];
if(myatts.indexOf(property) !== -1){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
每条评论更新:
如果您已经有一个以属性作为键的对象,则可以使用 Object.keys(),但一定要使用 hasOwnProperty
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
var property = "agility";
var text = "";
if(Object.keys(item.attribute).indexOf(property) !== -1){
if(item.attribute.hasOwnProperty(property)){
text = "+" + text + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
fiddle : http://jsfiddle.net/trex005/rk9j10bx/
更新回答预期的问题而不是提出的问题
如何将以下对象扩展为以下字符串?注意:属性是动态的。
对象:
var item = {};
item.attribute = {
agility:100,
stamina:200,
dodge:300
};
字符串:
+ 100 Agility + 200 Stamina + 300 Dodge
答案:
var text = "";
for(var property in item.attribute){
if(item.attribute.hasOwnProperty(property)){
if(text.length > 0) text += " ";
text += "+ " + item.attribute[property] + " " + property.charAt(0).toUpperCase() + property.substr(1);
}
}
关于javascript - 如何设置具有多个条件的if语句,在if语句中使用有效条件的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966805/