javascript 带有对象的Javascript三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27113329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript ternary operator with object
提问by lboyel
I came across a piece of code I am trying to figure out, the code basically stores the occurrence of the amount of time a word appears in a text document, so the function countWordsIntexttakes in the desired text and displays the word and the number of occurrence in the text, e.g would: 3 but: 5 very: 6
我遇到了一段我想弄清楚的代码,该代码基本上存储了一个单词在文本文档中出现的时间量,因此函数countWordsIntext接收所需的文本并显示单词和出现的次数出现在文本中,例如将:3 但:5 非常:6
while looking at the function that counts the word in the text I cant figure out how the conditional tenary operation is supposed to work. An explanation would be very much appreciated
在查看计算文本中单词的函数时,我无法弄清楚条件十进制操作应该如何工作。非常感谢解释
var wordCounts = {};
function countWordsInText(text) {
var words = text.toString()
.toLowerCase()
.split(/\W+)
.sort();
for(var index in words) {
var word = words[index];
if(word) {
wordCounts[word] =
(wordCounts[word]) ? wordCounts[word] + 1 : 1;
}
}
}
function display()
{
for (var index in wordCounts)
console.log(index + ': ' + wordCounts[index]);
}
I don't understand how the wordCounts[word]
object property is updated.
我不明白wordCounts[word]
对象属性是如何更新的。
回答by Paul S.
Say you have
说你有
var foo = {};
The line that is confusing you would be
令你困惑的那条线
foo.bar = foo.bar ? foo.bar + 1 : 1; // line A
Ask yourself
问你自己
- What is
foo.bar
at the start? It is undefined, we didn't givefoo
a property bar - What is
foo.bar
after the first time line A is executed? It is1
;foo.bar
was undefinedwhich is falsyso the ternary operator gave us back1
- What is
foo.bar
after the second time line A is executed? It is2
;foo.bar
was1
which is truthy, so the ternary operator gave us backfoo.bar + 1
- 什么是
foo.bar
在开始?它是undefined,我们没有给出foo
属性栏 - 什么是
foo.bar
第一次线后执行的?它是1
;foo.bar
在不确定的是falsy所以三元运营商提供给我们回1
- 什么是
foo.bar
第二次行之后被执行的?它是2
;foo.bar
是1
这是truthy,所以三元运营商提供给我们回foo.bar + 1
Line A can be repeated until you run out of numbers or the world explodes
A 行可以重复,直到你用完数字或世界爆炸
Writing it like this is a way to solve the undefined + 1
problem, which would give NaN
像这样写是解决undefined + 1
问题的一种方法,这会给NaN
An equally valid solution (which I find a bit cleaner to read personally) would be to do
一个同样有效的解决方案(我觉得个人阅读更清晰)是
foo.bar = (foo.bar || 0) + 1;