Search code examples
coffeescriptframerjs

How do I create a series of layers from an array and for loop?


Basically, I need to create layers from five images. Is there a way to do this with a for loop, as opposed to manually creating the layers? The following code was my attempt, but I'm not sure how to debug from here.

tabs_strings = ["nearby", "adopted", "my_cats", "settings", "bruce"]

for tab in [0..tabs_strings]
    tab = new Layer 
        x:0, y:0, width:640, height:1136, image:"images/#{tab}.jpg" 

# nearby = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/nearby.jpg"
# adopted = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/adopted.jpg", opacity: 0
# my_cats = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/my_cats.jpg", opacity: 0
# settings = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/settings.jpg", opacity: 0
# bruce = new Layer 
#   x:0, y:0, width:640, height:1136, image:"images/bruce.jpg", opacity: 0

Solution

  • Your for loop is, um, strange. tabs_strings is itself an array so you're saying:

    for i in [0 .. some_array]
    

    rather than the usual:

    for i in [0 .. some_number]
    

    or

    for e in some_array
    

    If you look at the JavaScript version, you'll see this:

    for (tab = _i = 0; 0 <= tabs_strings ? _i <= tabs_strings : _i >= tabs_strings; tab = 0 <= tabs_strings ? ++_i : --_i) {
    

    so you end up comparing 0 with an array and that's not terribly productive.

    I think you want to use the for e in array form of the for-loop:

    for tab in tab_strings
        new Layer 
            x:0, y:0, width:640, height:1136, image:"images/#{tab}.jpg" 
    

    There's no need for the tab assignment inside the loop so I took that out.