0

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?

2
  • what value would you expect to see? Commented Jul 16, 2010 at 2:45
  • When in doubt, try using Firebug to take a look. Commented Jul 16, 2010 at 2:48

5 Answers 5

6

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.