在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