2017-10-08 50 views
1

在Node.JS中將字典對象作爲MEAN堆棧項目的一部分工作時,遇到一些奇怪的行爲。條件語句中存在Javascript字典關鍵字

我在我的代碼定義keywordSearches字典早了,searchesSearch對象的數組包含keyword屬性。我基本上是從MongoDB中獲取所有搜索請求的記錄,然後創建一個包含關鍵字搜索頻率的字典,其中關鍵字是搜索文本,值是搜索頻率(整數) 。所有這些都存儲在keywordSearches。但是,當我使用下面的代碼來遍歷我的搜索時,我發現keywordSearches中的關鍵字在我的if條件之外評估爲false,但在if條件(下一行!)內顯然評估爲true。 。爲什麼會發生?

console.log(keywordSearches); 
    for (var i = 0; i < searches.length; i++){ 
    var keywords = searches[i].searchBody.keywords; 
    console.log(keywords in keywordSearches); // <- this evaluates to false 
    if (!keywords in keywordSearches){ // <- this section of code never executes! Why? 
     console.log("New keyword found") 
     keywordSearches[keywords] = 1; 
    } else { 
     keywordSearches[keywords] = keywordSearches[keywords] + 1; 
     console.log("else statement") 
    } 
    } 
    console.log(keywordSearches); 

輸出(注意,我有四個Search對象,都用關鍵字 「攝影」:

{} <- console.log(keywordSearches) 
false <- (keywords in keyWord Searches) 
else statement <- if condition evaluates to false! Should evaluate to true. Why? 
true 
else statement 
true 
else statement 
true 
else statement 
true 
else statement 
{ photography: NaN } 

我明白爲什麼photographyNaN:它從未與1值初始化(如果最初沒有在字典中找到它,那麼它應該是這樣)。因此它每次加入NaN + 1。

+0

這可能是運營商優先權問題。嘗試在if語句做的時候加上括號(keywodSearches中的關鍵字) – doze

回答

2

in具有比!的優先級低,所以你的表達被評價爲:

(!keywords) in keywordSearches 

代替:

!(keywords in keywordSearches) 

參見:Operator precedence上MDN

0

避免使用!完全,並切換if-else語句相反:

console.log(keywordSearches); 
for (var i = 0; i < searches.length; i++){ 
var keywords = searches[i].searchBody.keywords; 
console.log(keywords in keywordSearches); // <- this evaluates to false 
if (keywords in keywordSearches){ 
    keywordSearches[keywords] = keywordSearches[keywords] + 1; 
    console.log("keyword already exists") 
} else { 
    console.log("New keyword found") 
    keywordSearches[keywords] = 1; 
} 
} 
console.log(keywordSearches); 

這節省了操作。

+0

這個答案缺少爲什麼給定的代碼是* not * working。是的,交換分支會導致正確的功能,但正如另一個答案指出的那樣,問題的核心是關於不按預期運行的情況。 – mhoff