我一直在修改js中的散列计数器,而且我很难理解为什么预定义键为空会使累加器工作。
var totCounts = {};
Object.keys(repoCollection).forEach((x) => {
Object.keys(repoCollection[x]).forEach((y) => {
// If I remove this totCounts becomes a collection of Nans
// why do I need this
if(!totCounts[y]){
console.log('undef');
totCounts[y] = null;
}
totCounts[y] += repoCollection[x][y]
});
});repoCollection看起来是这样的,在这个例子中,缩写了很多次:
{
"HSchmale16/AccelLib": {
"C++": 4915,
"Arduino": 1580,
"Makefile": 786
},
"HSchmale16/better-nfsn-dotfiles": {
"Shell": 459,
"VimL": 241
},
"HSchmale16/CustomComputerChair": {
"C": 62477,
"C++": 52760,
"Assembly": 11862,
"Eagle": 10410,
"Prolog": 1297,
"Arduino": 500,
"Shell": 120
},
"HSchmale16/CalculusProject": {
"C++": 7661,
"TeX": 5870,
"Makefile": 828
},
"HSchmale16/econsim": {},
"HSchmale16/BoostVpthread": {
"C++": 2527,
"Perl": 2124,
"Makefile": 770
},
"HSchmale16/ConsoleMP": {
"C": 12525,
"Shell": 2109,
"C++": 1854,
"Makefile": 1359
},
"HSchmale16/ElectronChargeSim": {
"C++": 14588,
"C": 3188,
"Makefile": 736
},
"HSchmale16/GenericMakefile": {
"Makefile": 12223,
"C++": 164,
"C": 147
}
}发布于 2017-03-28 21:43:42
因为数字加未定义的是NaN,而数字加null是数字。JS强迫null进入0,undefined强制进入NaN。
有关详细信息,请参阅What exactly is Type Coercion in Javascript?。
console.log( undefined + 1 );
console.log( null + 1 );
将您的值初始化为0而不是null可能更有意义,但是JS对待它们是一样的(在这个场景中)。
https://stackoverflow.com/questions/43080476
复制相似问题