tags:

views:

34

answers:

5

Talk is cheap; I'd rather show the code:

//global var
var siblings = [];

var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined

Why undefined? What I basically want to achieve is to have a global object that would be a storage where info about other objects get saved. But get back to my problem. I pushed the value then I want to alert it but get undefined... why undefined?

+6  A: 

.push appends it to the array, siblings[0] contains it because it's the first element in (formerly) empty array.

If you want to determine the key yourself, do

siblings = {};
siblings['key'] = 'something';

Otherwise loop through the array if you want to access each element

for ( var l = siblings.length, i = 0; i<l; ++i ) {
   alert( siblings[i] )
}

Note: arrays are objects so I could've set siblings['key'] = 'something'; on the array, but that's not preferred.

meder
+2  A: 

siblings is an array. You're pushing the value 'uin_'+rand onto it, so the keys would then be 0. Instead, you'd want to create an object.

var siblings={};
var rand=+new Date();
siblings['uin_'+rand]="something";
alert(siblings['uin_' + rand]);
icktoofay
A: 

Because you pushed a string value to array index 0, then tried to get a non-existant property on the array object.

Try using Array.pop().

harto
A: 

In order to access an array, you need to use array indices, which basically refer to whether you want the 1st, 2nd, 3rd, etc.

In this case, use siblings[0].

Platinum Azure
A: 

Because siblings is an array, not an associative array. Two solutions:

//global var - use as an array
var siblings = [];

var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings[0]); // undefined

//global var - use as an associative array
var siblings = {};

var rand = new Date().getTime();
siblings.push('uin_' + rand);
alert(siblings['uin_' + rand]); // undefined
Igor Zevaka