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;
}
精彩评论