Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript index of array is array

I do not understand Javascript interpretation of the next lines of code:

var a = ["value"];
console.log(a[0]); // value
console.log(a[[0]]); // value
console.log(a[[[0]]]); // value
//...

Why is an array taken as the value 0?

like image 219
Rafael Páez Bastida Avatar asked Jun 21 '20 17:06

Rafael Páez Bastida


People also ask

Is index an array?

Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Is index in array JS?

If you've learned about indexing and manipulating strings in JavaScript, you may be familiar with the concept of indexing arrays already, as a string is similar to an array. Arrays do not have name/value pairs. Instead, they are indexed with integer values beginning with 0 .

How do you find the index of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

Is JavaScript array an array?

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays.


1 Answers

The bracket notation is used as property accessor, and is defined in the ECMAScript Language Specification, under chapter "Property Accessors". The expression between square brackets is processed in step 4 as:

EvaluatePropertyAccessWithExpressionKey(baseValue, Expression, strict).

...which in turn performs the following step:

ToPropertyKey(propertyNameValue).

...which in turn performs this step:

ToPrimitive(argument, hint String).

...which, if you drill down further in the specification will convert that expression to string if it is an object, using either the Symbol.toPrimitive (if it's defined) or the toString method. And yes, if the expression between the outermost brackets is an array (maybe nested), like [0], or [[0]], ...etc, you pass an object.

An array converted to string (with its toString() method) will produce a comma separated string of its values. This works recursively into nested arrays, so this practically means that all values, no matter how deeply nested, come out in the resulting comma separated string. For example [[1, 2], 3, [4, [5]]].toString() is "1,2,3,4,5".

In your examples, there is always just one value, 0, in the array that you pass as expression to the outer bracket pair. So that expression, such as [[[[[0]]]]].toString(), resolves to "0".

And so we get a["0"], which is the same thing as a[0].

like image 59
trincot Avatar answered Oct 19 '22 20:10

trincot