2017-10-08 45 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