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>
pushis a function. You call functions with(), not[]: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: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 writevar mycars = [];. It does the same thing but is more concise and not prone to side effects.