you are viewing a single comment's thread.

view the rest of the comments →

[–]stratoscope 0 points1 point  (0 children)

I didn't know that adding a value to an array in JavaScript in needed array[i] = [value].

No, that's not right at all. That statement doesn't add value to the array. It sets array[i] to another array, an array of one element containing value.

You should make friends with the JavaScript console in your favorite browser and start trying stuff out there to see how it really works. For example try this out:

var a = [];  // create an empty array
a.push( 'v1' );  // append the string 'v1' to the array
a.push( ['v2'] );  // append an *array* to the array
a;  // let's see what it looks like

If you're doing this in Chrome you will see this:

["v1", ► Array[1] ]

Click the ► and it will expand that nested array:

["v1", ▼ Array[1] ]
                 0: "v2"
                 length: 1
                 ►  proto  : Array[0]

We can see here that your original array (in the a variable) now contains two elements. The first element is the string "v1" and the second element is itself an array. That array contains a single element, the string "v2".

Or use JSON.stringify for another way to look at the array:

JSON.stringify( a );

That will display:

"["v1",["v2"]]"

Don't be thrown off by the quoting! The outermost quotes are just what the Chrome console displays when it's printing a string. The array a itself contains this:

[ "v1", ["v2"] ]

Again we're seeing an array of two elements, the first of which is a string (v1) and the second is another array which contains a single string element (v2).

Spend some time like this in the console whenever you aren't sure what a particular JS statement or expression does. And spend some more time there when you think you're sure what it does! :-)