Javascript ternary operator with object

lbo*_*yel 2 javascript arrays conditional-operator

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 countWordsIntext takes in the desired text and displays the word and the number of occurrence in the text, e.g would: 3 but: 5 very: 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]);
}
Run Code Online (Sandbox Code Playgroud)

I don't understand how the wordCounts[word] object property is updated.

Pau*_* S. 7

说你有

var foo = {};
Run Code Online (Sandbox Code Playgroud)

令你困惑的那条线

foo.bar = foo.bar ? foo.bar + 1 : 1; // line A
Run Code Online (Sandbox Code Playgroud)

问你自己

  1. 什么是foo.bar在开始?它是undefined,我们没有给出foo属性
  2. 什么是foo.bar第一次线后执行的?它是1; foo.bar不确定的falsy所以三元运营商提供给我们回1
  3. 什么是foo.bar第二次行之后被执行的?它是2; foo.bar1这是truthy,所以三元运营商提供给我们回foo.bar + 1

A 行可以重复,直到你用完数字或世界爆炸

像这样写是解决undefined + 1问题的一种方法,这会给NaN


一个同样有效的解决方案(我觉得个人阅读更清晰)是

foo.bar = (foo.bar || 0) + 1;
Run Code Online (Sandbox Code Playgroud)