条件语句中存在Javascript字典关键字

在使用Node.JS中的字典对象作为MEAN堆栈项目的一部分时,遇到了一些奇怪的行为。

我在代码的前面定义了一个keywordSearches字典, searches是一个包含keyword属性的Search对象数组。 我基本上是从MongoDB中获取所有search请求的logging,然后创build一个包含关键字search频率的字典,其中关键字是search文本,值是search频率(一个整数) 。 所有这些都存储在keywordSearches

然而,当我使用下面的代码遍历我的search,我看到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 。 (如果它最初在字典中没有find,它应该是这样的)。 所以每次都加NaN + 1

比…更有优先权! ,所以你的expression评估为:

 (!keywords) in keywordSearches 

代替:

 !(keywords in keywordSearches) 

请参阅:MDN上的运算符优先级

避免使用! 完全,并切换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); 

这节省了操作。