在Node.JS中將字典對象作爲MEAN堆棧項目的一部分工作時,遇到一些奇怪的行爲。條件語句中存在Javascript字典關鍵字
我在我的代碼定義keywordSearches
字典早了,searches
是Search
對象的數組包含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 }
我明白爲什麼photography
是NaN
:它從未與1
值初始化(如果最初沒有在字典中找到它,那麼它應該是這樣)。因此它每次加入NaN
+ 1。
這可能是運營商優先權問題。嘗試在if語句做的時候加上括號(keywodSearches中的關鍵字) – doze