Consider a class which contains a set of other objects.
function Food= (){ this.apples = 8; this.orange = 6; this.peach = 3; } Now, I can create an add function.
Food.prototype.add(food){ this.apple += food.apple; this.orange+=food.orange; this.peach+=food.peach; } However, what if I want to dynamically want to add in another thing into food, which food.prototype.add will also add?
The first question is, is there a simple way to add all the objects in the class?
The second question is this: I could have written the code as follows.
function Food = (){ this.apples = 8; this.orange = 6; this.peach = 3; this.addArray = []; this.addArray.push(this.apples); this.addArray.push(this.orange); this.addArray.push(this.peach); } Food.prototype.add(food){ for (i=0, i<this.addArray.length, i++){ this.addArray[i]+=food.addArray[i]; } } This way, if I want to add escargot to the things I want to add, I can simply add it to the addArray.
Is there a way I can make a similar addSet, or a addObject. So instead of an having an array with indexes, I can have a set or object with names instead?
Foodis actuallyFoodscontaining name and quantity pairs. You're on the right track, although your idea of using an object, rather than an array, seems like a lot better approach. (Here, by "a lot better approach", I mean the only one that makes any sense.)for(var item in obj) { ... }, although based on what you are trying to do a data structure like an array would be a better idea. Mainly due to if you want to add any other properties to food that might not be a number you want to "add".