在循环Coffescript中声明动态变量

时间:2016-11-02 15:47:33

标签: variables coffeescript framerjs

可能这是一个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 = new Layer ... 等等

我怎么能用CoffeeScript完成这个?

1 个答案:

答案 0 :(得分:0)

我不确定,但我认为你要做的是按名称获取对每个创建的图层的引用,对吧?您可以通过将它们存储在名称引用下的对象中来完成此操作:

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/

相关问题