【问题标题】:declaring dynamic variable in loop Coffescript在循环 Coffeescript 中声明动态变量
【发布时间】:2017-03-16 00:19:58
【问题描述】:

可能这是一个noobisch问题。目前我正在摆弄 Framer.js。我有一个 CoffeeScript 问题;

types = ["orange", "apple", "banana", "grapefruit", "pear"]
for i in types
    li = new TextLayer
        text: types
        y: li * 60
    li.parent = dropdownList

    print "list-item-" + "#{i}", i

所以我有一个数组,我想向一个对象实例声明一个动态变量。上面的代码只生成 5 个 li 层(这是 Framer 特定的 > 我不想在编辑器中使用非自我解释的层名称)

所以在for循环内;

var item-orange = new Layer...

var item-apple = 新层... 等等

我如何使用 CoffeeScript 来完成这项工作?

【问题讨论】:

  • 你的“编辑”是什么意思?为什么不为此使用对象 ({ orange: ..., apple: ... })?
  • 你想完成什么? y: li * 60 是什么意思,这不是 NaN 吗?为什么将整个数组类型分配为文本?该打印声明的意义何在?你能从预期和实际输出的角度解释你的问题吗?
  • 也许我应该去掉其余的 Framer 术语。基本上数组中的每个值都将添加到父下拉列表中,垂直间距为 60px。打印功能是在 Framer Studio 中执行 console.log 的一种方式。我正在做一些摆弄。使用“#{i}”是一种获取元素值的方法。 Framer.js 是一个带有名为 Framer Studio 的 IDE 的原型设计框架。

标签: variables coffeescript framerjs


【解决方案1】:

我不确定,但我认为您要做的是按名称获取对每个创建层的引用,对吗?您可以通过将它们存储在引用其名称的对象中来做到这一点:

types = ["orange", "apple", "banana", "grapefruit", "pear"]

# Create an empty layers object, outside of the loop
layers = {}

# Loop over the types array, storing the type in the variable named type
# And the number of the current loop in the variable index
for type, index  in types
    li = new Layer
        html: type
        y: index * 220
        name: "list-item-#{type}"
    # Store the layer in the layer object under the type key
    layers[type] = li 

    print "list-item-" + "#{type}", layers[type]

# Get a specific layer out of the layers array
layers['apple'].animate
    x: 300

完整示例在这里:http://share.framerjs.com/5owxrbz5hqse/

【讨论】:

  • 这样的例子很方便。在您的示例中,您将在 Framer Studio 中看到每个实例都被命名为 li。我想把它们看成层 list-item-orange、层 list-item-apple 等等。
  • 您可以通过使用name: 属性显式命名图层来完成此操作,我已更新示例以包含此内容。
  • 尼尔斯 非常感谢!
猜你喜欢
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
相关资源
最近更新 更多