Javascript 如何调用对象中每个对象的方法

Javascript 如何调用对象中每个对象的方法,javascript,object,for-loop,coffeescript,iteration,Javascript,Object,For Loop,Coffeescript,Iteration,我想迭代对象播放器中的对象项。Items是一组对象,其中每个对象都有一个add方法。当我使用它时,它会抛出一个错误,表示该项未定义。如何在每个项目上调用add for item of player.Items player.Items.item.add() 另外,我正在使用coffeescript,这不是任何语言中for循环的工作方式。循环变量直接引用,而不是固定在集合的末尾。您还错误地使用了;如果项是数组,则需要使用for/in: 您可以将其写成一个简单的数组理解: item.add

我想迭代对象播放器中的对象项。Items是一组对象,其中每个对象都有一个add方法。当我使用它时,它会抛出一个错误,表示该项未定义。如何在每个项目上调用add

for item of player.Items
    player.Items.item.add()

另外,我正在使用coffeescript,这不是任何语言中for循环的工作方式。循环变量直接引用,而不是固定在集合的末尾。您还错误地使用了;如果项是数组,则需要使用for/in:

您可以将其写成一个简单的数组理解:

item.add() for item in player.Items

最后,CoffeeScript和JavaScript中有一个强大的约定:您应该只使用大写字母来表示类,而不是变量。您的集合应称为player.items。

这不是for循环在任何语言中的工作方式。循环变量直接引用,而不是固定在集合的末尾。您还错误地使用了;如果项是数组,则需要使用for/in:

您可以将其写成一个简单的数组理解:

item.add() for item in player.Items
最后,CoffeeScript和JavaScript中有一个强大的约定:您应该只使用大写字母来表示类,而不是变量。您的收藏应称为player.items

也许是这个? 我不知道cofeescript是如何解析或工作的,所以这只是一个猜测

也许是这个?
我不知道cofeescript是如何解析或工作的,所以这只是一个猜测。

您使用的循环不正确。我建议您看看CoffeeScript,了解for循环如何在CS中工作

取决于player.Items是数组还是对象

对于阵列:

# Loop through the individual elements in the Array, where
# each element is assigned to the item variable
item.add() for item in player.Items
对于对象:

# 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
您的代码使用对象迭代器形式,但只指定了一个变量,其中for循环将分配两条信息,因此您的item变量只是一个字符串或一个数字,具体取决于播放器。Items实际上是什么


其次,即使您正确定义了for循环,代码也会失败,因为您正在引用一个名为item of player.Items的变量。如果是对象,则必须使用player.Items[key].add、item.add,如果是数组,则只能使用item.add。

循环使用不正确。我建议您看看CoffeeScript,了解for循环如何在CS中工作

取决于player.Items是数组还是对象

对于阵列:

# Loop through the individual elements in the Array, where
# each element is assigned to the item variable
item.add() for item in player.Items
对于对象:

# 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
您的代码使用对象迭代器形式,但只指定了一个变量,其中for循环将分配两条信息,因此您的item变量只是一个字符串或一个数字,具体取决于播放器。Items实际上是什么


其次,即使您正确定义了for循环,代码也会失败,因为您正在引用一个名为item of player.Items的变量。如果是对象,则必须使用player.Items[key].add、item.add,如果是数组,则只能使用item.add。

Items包含对象,因此我应该使用,当我将代码更改为您的代码时,它会抛出一个错误,说明该项没有add方法。如果Items是数组,则需要输入。不管它是什么数组,不管是对象、嵌套数组、字符串还是数字。但是,如果Items本身是一个对象,而不是数组,那么使用:item.add for i,item of player.ItemsItems包含对象,因此我应该使用,当我将代码更改为您的代码时,它会抛出一个错误,说明该项没有方法add。如果Items是数组,则需要输入。不管它是什么数组,不管是对象、嵌套数组、字符串还是数字。但是,如果Items本身是一个对象,而不是数组,那么使用:item.add for i,item of player.Items你可以给出一个player对象的真实示例,add方法做什么?你能给出一个player对象的真实示例吗,add方法做什么?