if块中这些代码之间的区别

我在这里得到了预期的结果。

 var modeObj = {};

array.forEach(num => {
    if (!modeObj[num])
        modeObj[num] = 0;
        modeObj[num]++;
});

我在这里得到空结果。

var modeObj = {};

array.forEach(num => {
    if (!modeObj[num]) {
        modeObj[num] = 0;
    }else {
        modeObj[num]++;
    }

});

上面的代码与下面的代码有什么不同?我在if条件中缺少一些概念。

评论
  • 紫涙嘫
    紫涙嘫 回复

    When you have if/else - the line inside the else block will only gets evaluated when the value of the if is false.

    在第一个示例中-无论if是否有效,第二行都会每次运行。

    If you don't have brackets - only the next line (after the if) is evaluated.
    Your first example is actually the following:

    var modeObj = {};
    
    array.forEach(num => {
        if (!modeObj[num]) {
            modeObj[num] = 0;
        }
        modeObj[num]++;
    });
    
  • 娇气的小奶包
    娇气的小奶包 回复

    The first code if condition does not have {}. Hence only the first line is executed and the line modeObj[num]++; is executed no matter what the result of the if condition is.

    在第二个代码中,您添加了else。

  • 小笨蛋o
    小笨蛋o 回复

    You're increasing modeObj[num]++ outside if part of the conditional & the second code snippet. It should be like so instead:

    var modeObj = {};
    
    array.forEach(num => {
        if (!modeObj[num]) {
            modeObj[num] = 0;
            modeObj[num]++;
        } else {
           // do something
        }
    
    });