Reputation: 361
I would like to reduce amount of IF statements in my code:
Too many properties are repeated which is a problem.
Second part which may relate to the code above. I would like to iterate through my object properties:
myObject ={
property_1: myValue_1,
property_2: myValue_2,
otherProperty_1: myValue_1
};
Based on an object above, I want to iterate only through property_1, property_2
, ignoring otherProperty_1
.
My object can have "property_x" properties up to 5 of them, or none at all. I was trying to make an if statement which would be something like this pseudo code:
for(var statName in myObject){
If(myObject has any property called : 'property_1, property_2, property_3, property_4, property_5'.indexOf(statName) != -1;)
//Then display in html: '<img src="images/' + property_x(where x is a property 1/2/3/4 or 5) and it would display only available properties in current object. I can make it work with an 5x if else statements to check for every property, since there cannot be property_1 and property_3/4/5 if "2" is missing. I was looking for a better way to display it.
}
}
Answer using JavaScript would be the best, but jQuery us an option too.
Any links with material I can use to learn more are welcome.
Thanks
Upvotes: 0
Views: 74
Reputation: 158
I'm not sure if i fully understand, but your pseudocode is actually pretty much valid :-). You can iterate through each object properties using for prop in obj
statement ( you should also check if it's object own property ), and get the value of this property using obj[prop]
code.
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
html += '<img src="' + obj[prop] + '" />';
}
}
Here's the fiddle for that http://jsfiddle.net/b0ftLujj/1/
Upvotes: 1
Reputation: 35670
Not sure I understand the second part of your question, but here's a simplified version of your fiddle:
var randomNumber = Math.floor((Math.random() * 100) + 1);
if (dropItem.itemType === "weapon") {
dropItem["materiaSlot_1"] = 'empty';
if (randomNumber >= 40) dropItem["materiaSlot_2"] = 'empty';
if (randomNumber >= 60) dropItem["materiaSlot_3"] = 'empty';
if (randomNumber >= 80) dropItem["materiaSlot_4"] = 'empty';
if (randomNumber >= 95) dropItem["materiaSlot_5"] = 'empty';
};
Upvotes: 1