1

I've created an array in JavaScript and inserted objects with keys of object_ids:

var ar = [];

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Problem is when I print this out the array I get is:

[undefined, undefined, "b", undefined, "a", "d", undefined, undefined, "c"]

and

ar.length = 9

How do I prevent the array from auto filling with undefined values and simply save this array as a 4-element array?

Iteration over an array is not what I expect here.

Thanks!

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
hsz
  • 148,279
  • 62
  • 259
  • 315

6 Answers6

3

You can use an object literal instead of an array

var ar = {};
ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';
// {"2":"b","4":"a","5":"d","8":"c"}

You can iterate like this:

for (var i in a) {
    console.log(a[i]);
}
Dennis
  • 32,200
  • 11
  • 64
  • 79
2

Here's what you are doing:

var ar = [];
ar[8] = 'c'; // creates [undefined, undefined, undefined, undefined, undefined, undefined, undefined, 'c'];

I believe this is what you want:

var ar = {};

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Object.keys(ar).length == 4; // true

More information on Object.keys

Joe
  • 80,724
  • 18
  • 127
  • 145
  • This might sound like nitpicking but perhaps it's worth noting that `ar` is actually not an array here. – pimvdb Aug 23 '11 at 19:41
  • @pimvdb, it could be argued too that javascript arrays are in fact not really arrays either, but specialized javascript objects. – Joe Aug 23 '11 at 19:46
  • @Joey: At least arrays are also called arrays, but it does not matter much anyhow. – pimvdb Aug 23 '11 at 19:47
  • @pimvdb, I agree with you. I'm just being needless semantical – Joe Aug 23 '11 at 19:51
1

I think you are confusing the behavior of JavaScript Arrays with the associative-array behavior of all JavaScript objects. Try this instead:

var a = {};
a[4] = 'a';
a[2] = 'b';
a[8] = 'c';
a[5] = 'd';
a; // {'2':'b', '4':'a', '8':'c', '5':'d'}

Note that the key/value pairs in an object are not ordered in any way. To order the keys or values you must maintain your own array of ordering.

maerics
  • 151,642
  • 46
  • 269
  • 291
0

what you want to do is probably:

array = {}
array["1"] = "b"
array["7"] = "aaa"

now array is:

 Object { 1="a", 7="b"}

is it right?

mkk
  • 7,583
  • 7
  • 46
  • 62
0
var arr = {
    0 : "hello",
    8 : "world",
    14: "!"
    };

var count = 0;
for (var k in arr) {
   ++count;
}

document.write(arr[0] + " " + arr[8] + arr[14] + " with a length of " + count );

Outputs hello world! with a length of 3

You can use an Object.. and here is how to collect the count (if you needed)

Fiddle

rlemon
  • 17,518
  • 14
  • 92
  • 123
0

There is no guarantee that iterating an Object using the for...in statement be in any specific order. The behavior is undefined in ECMA Script specification, quote:

The mechanics of enumerating the properties ... is implementation dependent.

Chrome doesn't iterate elements in order in many cases, last time I checked Opera went the same way and just now I read here that IE9 has adopted the same behavior. So your only solution that is guaranteed to keep both the association and order of elements is to use an Object to store keys and values and an Array to store the order:

var obj = { 4: 'a', 2: 'b', 8: 'c', 5: 'd' };
var order = [ 4, 2, 8, 5 ];

for( var i in order ) {
    //do something with obj[ order[i] ]
}
nobody
  • 10,599
  • 4
  • 26
  • 43
  • No longer true as of ES2015. See [Does ES6 introduce a well-defined order of enumeration for object properties?](https://stackoverflow.com/q/30076219/215552) – Heretic Monkey Aug 19 '22 at 12:20