Jsrobby
Jsrobby

Reputation: 1

Getting undefined value from an array

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?

Upvotes: 0

Views: 794

Answers (5)

Igor Zevaka
Igor Zevaka

Reputation: 76500

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

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46183

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].

Upvotes: 0

harto
harto

Reputation: 90483

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().

Upvotes: 0

icktoofay
icktoofay

Reputation: 129001

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]);

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

.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.

Upvotes: 6

Related Questions