0

OK.. I really must be crazy. Why would these not print out 3-5 for "a"? I've tried two different methodologies to have the array store 3-5 below, and both of them seem.. obvious. There must be something in the underlying translation that I'm just not seeing.

<script>
    var articlesKey = [];
    for(var i = 3; i < 6; i++) {
        articlesKey.push(i);
        document.write('<br>i:'+i);
    }
    for (a in articlesKey)
        document.write("<br>a:"+a);


    articlesKey = [];
    var count = 0;
    for(var i = 3; i < 6; i++) {
        articlesKey[count] = i;
        document.write('<br>i:'+i);
        count++;
    }
    for (a in articlesKey)
        document.write("<br>a:"+a);
</script>

It prints out:

i:3
i:4
i:5
a:0
a:1
a:2
i:3
i:4
i:5
a:0
a:1
a:2

2 Answers 2

3

for( a in articlesKey) iterates a through the KEYS of articlesKey (letting you then get the values as articlesKey[a]). There is nothing wrong here.

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

Comments

0

That's very simply because a represents the array index in the loop, not the value at the index. Fix:

document.write("<br>a:"+articlesKey[a]);

Comments

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.