0

下面的东西可以干一点吗?

if(totals[label]) {
    totals[label] += increment;
} else {
    totals[label] = increment;
}

基本上,我有一个特殊情况 when totals[label] === undefined,因为undefined + increment === NaN无论何时typeof increment === 'number'

4

2 回答 2

3
totals[label] = (totals[label] || 0) + increment;
于 2013-02-13T22:57:57.810 回答
1

我觉得完全没问题,你没有重复太多。是的,你可以使用

totals[label] = (totals[label] || 0) + increment;

但恕我直言,这并没有节省多少。我认为

if (label in totals)
    totals[label] += increment;
else
    totals[label] = increment;

更容易阅读,因为它更好地表达了您想要做的事情。

于 2013-02-13T22:59:46.500 回答