开发者

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]); // undefin开发者_如何转开发ed

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?


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


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


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜