开发者

Grab reference, setting default value

Is the following code safe? How would you accomplish the same thing?

Say I have an object x. I want to add some values to an array for a key in x, setting that key to the empty arr开发者_开发技巧ay if it's not already there:

var x = {};
var a = x['k'] = x['k'] || [];
a.push('moo');


Try this?

var x = {}, a = 'k' in x ? x['k'] : [];

EDIT:

var x = {}, a = [];

if ( x['k'] ) {
    a = x['k'];
} else {
    x['k'] = a;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜