Chris Wijaya Chris Wijaya - 7 months ago 27
Javascript Question

Unregistered member of array in length property JS

I came across this code that is used to keep both forward and reverse reference in an array:

var arr = [];
arr[arr['A'] = 0] = 'A';
arr[arr['B'] = 1] = 'B';

// On node interpreter
arr // [ 'A', 'B', A: 0, B: 1 ]
arr["A"] // 0
arr["B"] // 1
arr[0] // 'A'
arr[1] // 'B'
arr[2] // 'undefined'
arr.length // 2

A: 0, B: 1
members get pushed to the end of the array.

What are these members and what happened in the process so that
property recorded 2 instead of 4?


Storing a value with a string key into an array does not actually modify the array. It only adds a dynamic field to the Array object, unlike storing with a numeric index, which actually pushes a value into the array.. Array.length only reflects the number of elements in the array, as managed by the array, but not the number of dynamic fields in the array.