1

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

The 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 .length property recorded 2 instead of 4?

Chris Wijaya
  • 1,276
  • 3
  • 16
  • 34
  • `"A"` is not really a valid index for an array – adeneo Sep 18 '16 at 04:25
  • http://stackoverflow.com/a/1076748/1005215 – Nehal J Wani Sep 18 '16 at 04:26
  • This should be treated as an ugly hack. While clever, it's ineffective as soon as the value being stored happens to be an integer. Use a separate object for storing the reverse references. – 4castle Sep 18 '16 at 04:39
  • @ChrisWijaya Didn't you read the answer? arr["fancy"]="what?"; is not included in the array length. – Nehal J Wani Sep 18 '16 at 04:40
  • @4castle the method is used by typescript to be able to self reference enum, the value can be various. I see your point, I would personally avoid writing this way in my scripts. – Chris Wijaya Sep 18 '16 at 05:06

2 Answers2

1

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.

SOFe
  • 7,867
  • 4
  • 33
  • 61
0
var arr = [];
arr["A"] = 2;

Here you are adding a property to the array object which does not reflect over the number of elements in the array.In javascript, elements of array are always stored using indices. Array.length always returns the number of elements stored in the array.

ninjawarrior
  • 328
  • 1
  • 7