开发者

Grab reference, setting default value

开发者 https://www.devze.com 2023-02-09 21:26 出处:网络
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 i

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

精彩评论

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