2017-03-28 28 views
1

我一直在用js中的哈希計數器擺弄,而且我很難理解爲什麼將鍵預定義爲null會使累加器起作用。簡稱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 
    } 
} 
+0

它應該用'0'來初始化,而不是'null'。 – Bergi

回答

3

由於數加上不確定的是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會將它們相同(在這種情況下)。

相關問題