0

When I try to push elements into a javascript array, it doesn't work. This is the simplest sample I can come up with. Why doesn't this work?

    <!DOCTYPE html>
    <html>
    <body>

    <script>
    var i;
    var mycars = new Array();

    for(i=1;i<=10;i++){
      mycars.push[ i.toString()+"-" ];
    }

    alert(mycars.join(""));

    </script>

    </body>
    </html>

1 Answer 1

3

push is a function. You call functions with (), not []:

mycars.push( i.toString()+"-" );
// here ---^     and here ----^

Where you probably got confused is that you can add to an array without using push, just by assigning to an array element, even if that element doesn't exist yet. So for instance, your loop could look like this:

for(i=1;i<=10;i++){
  mycars[mycars.length] = i.toString()+"-";
}

There, because I'm referring to an array element (mycars[mycars.length]), not calling a function, I use [].

Side note: Rather than var mycars = new Array();, just write var mycars = [];. It does the same thing but is more concise and not prone to side effects.

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

2 Comments

If I didn't know better with that kind of speed I'd say you were Jon Skeet.

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.