0

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++

1
  • 1
    Yes, you have to do it yourself. CS's for ... of loop is just a JavaScript for ... in loop in disguise. An index option in the CS for ... in loop make sense because you're iterating over something inherently ordered; an index when iterating over an object makes less sense because objects are inherently unordered so the index has no useful relation to what you're iterating over. Commented May 27, 2014 at 0:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I do have to loop on the colors, but I want to have an index for every colors, not only the key. I would like to be able to access a variable that increment on the loop... Example: red = 0, blue = 1, etc. Do I have to create that index myself or is there a way to have it automatically?
An index doesn't really make sense here because the standard does not determine an object property order. You should add an index manually.
Thanks, thats what I wanted to know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.