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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:57:51  来源:igfitidea点击:

Javascript ternary operator with object

javascriptarraysconditional-operator

提问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

问你自己

  1. What is foo.barat the start? It is undefined, we didn't give fooa property bar
  2. What is foo.barafter the first time line A is executed? It is 1; foo.barwas undefinedwhich is falsyso the ternary operator gave us back 1
  3. What is foo.barafter the second time line A is executed? It is 2; foo.barwas 1which is truthy, so the ternary operator gave us back foo.bar + 1
  1. 什么是foo.bar在开始?它是undefined,我们没有给出foo属性
  2. 什么是foo.bar第一次线后执行的?它是1; foo.bar不确定的falsy所以三元运营商提供给我们回1
  3. 什么是foo.bar第二次行之后被执行的?它是2; foo.bar1这是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 + 1problem, 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;