【问题标题】:Coffeescript Accessing a previously created object based on information in an arrayCoffeescript 根据数组中的信息访问先前创建的对象
【发布时间】:2014-03-17 05:35:10
【问题描述】:

我已经开始根据数组中的信息创建一系列对象,但后来无法使用数组信息来回调对象。这可能只是正确使用括号的问题:

total = 0
for item in @timelineArray
    # This prints the object that was previously created
    console.log Opening

    # This prints the clip length for that object
    console.log Opening.getClipLengthOutMinusIn()

    # This prints the word Opening which is the first item in the timeline array
    console.log item.name

    # This yields an error "TypeError: Object Opening has no method 'getClipLengthOutMinusIn'"
    total += (item.name).getClipLengthOutMinusIn()

提前感谢您的帮助。

【问题讨论】:

  • 所以你有一个变量Opening 在范围内,然后item.name 将是该变量的名称(Opening)?

标签: arrays object coffeescript


【解决方案1】:

解决“当变量名在字符串中时如何访问变量”问题的常用方法是在对象中构建自己的命名空间:

names =
    Opening: whatever_Opening_was_set_to
    ...

然后您可以通过名称访问names 中的值:

total += names[item.name].getClipLengthOutMinusIn()

您也可以使用eval,但这几乎总是一件可怕的事情。

【讨论】:

    猜你喜欢
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2020-07-22
    • 2020-09-20
    • 2013-06-05
    相关资源
    最近更新 更多