1

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 understanding.

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?

1

2 Answers 2

2

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.

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

Comments

2
> a = [1, 3, 5]
> a.push(7)
> a
[1, 3, 5, 7]

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.