top | item 1543880

Understanding JavaScript Arrays

34 points| heseltine | 15 years ago |javascriptweblog.wordpress.com | reply

14 comments

order
[+] svnv|15 years ago|reply
Isn't this faster for iterating over the elements:

  var a = ["banana", Math.min, 4, "apple"];
  for (var i=a.length; i; i--) {
    console.log(a[i]);
  }
[+] svnv|15 years ago|reply
Actually, I just realized this does not work, there is an off by 1 error here. jacksoncarter's piece of code works though.
[+] jacksoncarter|15 years ago|reply
Or try this

  var i = a.length;
  while (i--){
    console.log(a[i]);
  }
[+] pooj|15 years ago|reply
Clever, but sometimes you don't want to go in reverse.
[+] ccollins|15 years ago|reply
I want to stress that the following will work, but get you in trouble. Javascript does not support associative arrays.

  var myData = new Array;

  myData['key1'] = 'value1';
  myData['key2'] = 'value2';
  myData['key3'] = 'value3';

  myData.length; //0
[+] olavk|15 years ago|reply
I would say that JS does support associative arrays, since it is the fundamental data type behind objects and arrays. Arrays are basically associative arrays, since the index is converted into a string and used as a key. E.g. myData[7] is equivalent to myData["7"].

The length property does not return the number of items in the array though. It returns the value of the key with the highest numerical value if parsed as a integer plus one.

[+] messel|15 years ago|reply
forEach,map, and several other ECMA5 methods look like a joy to use
[+] msie|15 years ago|reply
This isn't your father's Array. Sigh.