简体   繁体   中英

How to get the index in an associative array loop coffeescript

I've been looking for answers for quite some time now and none of what I've seen is right for my situation. Here is my code:

colors: 
    red : "255, 0, 0"
    blue : "24, 149, 207"
    green : "74, 165, 76"
    grey : "202, 202, 202"
    black : "0, 0, 0"
    yellow : "183, 118, 4"
    purple : "83, 74, 166"
    white : "255, 255, 255"


for color, rgb, index of colors
 console.log index

I know that it is not working and I've seen many post about a simple array with a loop that looks like that:

for color, index in colors
    console.log index

I'm wondering if there is a way to do something like that with associative array or if I have to create define an index variable like this:

index: 0
for color, rgb of colors
    console.log index
    index++

Not sure if I understand your problem correctly. Do you want to loop over all your colors? Then do it like this:

colors =
    red : "255, 0, 0"
    blue : "24, 149, 207"

index = 0
for color, rgb of colors
    console.log color
    console.log rgb
    console.log index
    index++

Note that you have to use colors = instead of colors: to define a variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM