How to achieve this similar functionality with arrays from PHP in JS
In PHP its possible to do the following:
$array[] = 1;
$array[] = 2;
And on its own, you will end up with:
$array[0] === 1;
$array[1] === 2;
With JS however, this isn't so simple. At least from my unde开发者_如何学编程rstanding.
It seems you need to firstly start the array
var array = new Array();
Then:
array[0] = 1;
array[1] = 2;
Due to my php (and quite inferior) background, the way I've constructed my JS function I can only see it working if I can set array variables in a similar way to its possible in php.
Is it possible to achieve this same functionality? If so, how?
First you create the array, which you can do with new Array()
if you like, but usually it's better just to use an empty literal:
var array = [];
Then you can do what you did, or use push
:
array.push(1);
array.push(2);
push
is basically this:
array[array.length] = n;
Sometimes you'll see people actually do that directly in their code, because on some implementations it was actually faster.
If you have all of this data to hand originally, you can do this:
var array = [1, 2];
...which creates the array via an array literal and then assigns the result to the variable.
> a = [1, 3, 5]
> a.push(7)
> a
[1, 3, 5, 7]
精彩评论