player.Items[item].add();
Maybe this? I don't know how cofeescript parse this (or work at all) so It's just a wild guess.
Question
I want to iterate the object Items
inside of the object player
. Items
is a set of objects in which each of them have a method add
. When I use this it throws an error saying that item is undefined. How can I call add
on each item?
for item of player.Items
player.Items.item.add()
P.S. I am using coffeescript
Solution
player.Items[item].add();
Maybe this? I don't know how cofeescript parse this (or work at all) so It's just a wild guess.
OTHER TIPS
You are using the loop incorrectly. I suggest you take a look at CoffeeScript's documentation to understand how for loops work in CS.
Depending whether player.Items is an Array or Object...
For Arrays:
# Loop through the individual elements in the Array, where
# each element is assigned to the item variable
item.add() for item in player.Items
For Objects:
# Loop through the Object's enumerable keys, assigning the key's name to key variable
# and the key's contents (another Object, I assume) to the item variable
item.add() for key,item of player.Items
Your code is using the Object iterator form but only specifies one variable where the for loop is expected to assign two pieces of information and so your item
variable is just a string or a number ( depending on what player.Items actually is ).
Secondly, even if you defined the for loop correctly, your code would fail, because you are referencing a variable called item
of player.Items
. In case of Objects, You would have to either use player.Items[key].add()
, item.add()
or in case of Arrays simply item.add()
.
That isn't how for loops work in any language. The looping variable is referenced directly, not tacked onto the end of the collection. You're also using of
incorrectly; if Items
is an array, you need to use for/in
:
for item in player.Items
item.add()
You can write this as a simple array comprehension:
item.add() for item in player.Items
Lastly, there is a strong convention in CoffeeScript and JavaScript: You should only be using uppercase letters to denote classes, never variables. Your collection should be called player.items
.