3

so I encountered weird problem here. I have an array status=new Array(). Then I iterate from 0 to N-1, and assign status[i]="idle"; I tried to do alert to check the values, and they are all assigned to a character coma ,. Anyone knows what's wrong?

var status=new Array();
window.onload = function() {
    for(var i=0;i<5;i++) {
        status[i]="idle";
        alert(status[i]);
    }
}
0

1 Answer 1

7

Use a different variable name (or better yet, don't use global variables at all). There's a window.status property already, and apparently something isn't letting you shadow it with your own (which surprises me slightly; I wonder if the array is being coerced to a string on assignment or something). At global scope, var creates properties on the window object, which is why window.status is relevant.

This example (source) replicates your problem (for me, using Chrome), and this example (source) with just a changed name shows the correct series of alerts.

Note that this is browser-specific. On Firefox, even your old code shows me the correct series of alerts. E.g., Firefox is allowing us to redefine window.status, but Chrome isn't.

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

4 Comments

Yeah, there's a window.status property which may be overshadowing it. But when I just copied it to a fiddle, it works fine for me. Here's the link: jsfiddle.net/wGzv9
@gopi1410: It seems to be browser-specific. I get a series of "undefined" alerts in Chrome, but the correct "idle" alerts in Firefox. Other browsers probably do other things. At the end of the day, probably best to avoid the global. :-)
@gopi1410: Re your fiddle: jsFiddle wraps your code in a function by default, so var status in your fiddle isn't creating a global variable. If you do a "view frame source" on the result pane, you'll see what I mean.
@T.J.Crowder oh, got it! I was wondering it works fine for me in chrome too, now I see. Thanks. :)

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.