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

How to call method of each object within an object

本文关键字:对象 方法 调用 一个对象      更新时间:2023-09-26

我想在对象player中迭代对象ItemsItems是一组对象,其中每个对象都有一个方法add。当我使用这个时,它抛出一个错误,说项目是未定义的。我如何在每个项目上调用add ?

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

注:我用的是coffeescript

player.Items[item].add();

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

您错误地使用了循环。我建议你看一下CoffeeScript的文档,以了解CS中的for循环是如何工作的。

取决于玩家是否。

数组:

# 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变量只是一个字符串或一个数字(取决于什么播放器。

其次,即使你正确地定义了for循环,你的代码也会失败,因为你引用了一个叫做player.Itemsitem的变量。在对象的情况下,您必须使用player.Items[key].add(), item.add()或在数组的情况下,只需item.add()

这不是任何语言中for循环的工作方式。循环变量是直接引用的,而不是附加到集合的末尾。你也不正确地使用of;如果Items是一个数组,则需要使用for/in:

for item in player.Items
   item.add()

你可以把它写成一个简单的数组推导式:

item.add() for item in player.Items

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