【问题标题】:How to call method of each object within an object如何调用对象内每个对象的方法
【发布时间】:2014-04-12 02:31:11
【问题描述】:

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

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

附:我正在使用咖啡脚本

【问题讨论】:

  • 能否举个播放器对象的真实例子,add()方法是做什么的?

标签: javascript object for-loop coffeescript iteration


【解决方案1】:

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

for item in player.Items
   item.add()

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

item.add() for item in player.Items

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

【讨论】:

  • Items 包含对象,所以我应该使用 of,当我将代码更改为您的代码时,它会抛出一个错误,指出该项目没有方法 add
  • 如果Items是一个数组,你需要in。它是什么数组并不重要,它是对象还是嵌套数组、字符串或数字。但是,如果Items 本身是一个对象,而不是一个数组,那么使用ofitem.add() for i,item of player.Items
【解决方案2】:
player.Items[item].add();

也许是这个? 我不知道 cofeescript 如何解析这个(或根本工作)所以这只是一个疯狂的猜测。

【讨论】:

    【解决方案3】:

    您错误地使用了循环。我建议你看看 CoffeeScript 的 documentation 以了解 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 变量只是一个字符串或一个数字(取决于实际的 player.Items是)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 2022-12-09
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2016-02-11
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多