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

Javascript字典键存在于条件语句中,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,作为MEAN stack项目的一部分,在Node.JS中使用dictionary对象时,我遇到了一些奇怪的行为 我在前面的代码中定义了一个keywordSearches字典,searches是一个Search对象数组,其中包含关键字属性。我基本上是从MongoDB中提取所有搜索请求的记录,然后创建一个包含关键字搜索频率的字典,其中键是搜索文本,值是搜索频率(整数)。所有这些都存储在关键字搜索中 但是,当我使用下面的代码迭代搜索时,我看到keywordSearches中的关键字在if条件外的值为f

作为MEAN stack项目的一部分,在Node.JS中使用dictionary对象时,我遇到了一些奇怪的行为

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

但是,当我使用下面的代码迭代搜索时,我看到
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);

我理解为什么
photography
NaN
:它从来没有用
1
值初始化过。(如果最初在字典中找不到,则应该这样做)。因此,它每次都添加
NaN
+1。

中的
优先级低于
,因此表达式的计算结果为:

(!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);
console.log(关键字搜索);
for(var i=0;iconsole.log(关键字搜索中的关键字);//这可能是一个运算符前置问题。请尝试在if语句doing!(关键字搜索中的关键字)上添加括号这个答案缺乏给定代码不工作的原因。是的,交换分支可以获得正确的功能,但正如另一个答案所指出的,问题的核心是关于未按预期运行的情况。
 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);