I’m trying to learn JavaScript arrays, and I’m having trouble duplicating how I’ve been creating arrays in PHP:
$fruits[] = 'banana';
$fruits[] = 'orange';
Doing that in PHP automatically gives banana the key of 0 and orange the key of 1. But when I’m trying to do it in JavaScript, it doesn’t seem to automatically assign the key:
var fruits = [];
fruits[] = 'banana';
fruits[] = 'orange';
That doesn’t work. But this does:
var fruits = [];
fruits[0] = 'banana';
fruits[1] = 'orange';
Am I missing something? It seems kind of silly that you’d need to manually create the keys. This notation also seems ok:
var fruits = [ 'banana', 'orange' ];
But for my purposes, I’m trying to convert a big array from PHP to JavaScript, and life would be much easier if the second example worked. Is my notation slightly off, or are the last two examples the only ways to do it? Thanks in advance!
Use the array.push.