如果没有,Javascript分配变量?

时间:2011-10-26 08:01:12

标签: javascript variable-assignment assignment-operator

如果Javascript的计算结果为false,那么Javascript中是否有一些简写来分配变量?

在红宝石中,我可以这样做:

foo |= "bar"

如果foo的计算结果为false,则将“bar”指定给foo 所以像这样:(使用那个| =运算符)

var cars_by_brand_and_color = {};
for (var car in parking_lot) {
   // add a brand if it doesn't exist yet;
   // cars_by_brand_and_color['chevrolet'] = {};
   cars_by_brand_and_color[car['brand']] |= {};
   // and add that color to the brand if it doesn't exist yet;
   // cars_by_brand_and_color['chevrolet']['grey'] |= {}; 
   cars_by_brand_and_color[car['brand']][car['color']] |= {};
   // now let's add that car; 
   // cars_by_brand_and_color['chevrolet']['grey']['BDB-565'] = 'Mr. Smith';
   cars_by_brand_and_color[car['brand']][car['color']][car['lisence_plate']] = car['owner']
};

1 个答案:

答案 0 :(得分:5)

当然,JS语法是

var toAssign = mayBeNull || {};