假设我有一个单词数组,我想用一个对象来计算它。我试过这个:
exit
在这种情况下, const results = {};
const words = ["word", "hello", "code", "five", "hello", "word", "new", "code"];
words.forEach( word => {
results[word] = results[word] + 1 || 1;
});
返回:
results
{ word: 2, hello: 2, code: 2, five: 1, new: 1 }
是NaN === false
和false
。我不太明白为什么结果不会:
results[word] + 1 => NaN
有人在意解释吗? :)
答案 0 :(得分:3)
results[word]
不包含results
时,{p> word
为undefined
。虽然NaN === false
是false
,但它仍然是假值(!!NaN
是false
)。
因此,results[word] + 1 || 1
= undefined + 1 || 1
= NaN || 1
= 1
。
答案 1 :(得分:-1)
undefined
+ 1
= NaN
results[word] = results[word] + 1 || 1;
您正在初始化||处的值(或)操作将默认值设置为1而不是0.我解决这个问题的方法就像这样包装条件:
results[word] = (results[word] || 0)+1;