我在这里得到了预期的结果。
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 theelse
block will only gets evaluated when the value of theif
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:
The first code if condition does not have
{}
. Hence only the first line is executed and the linemodeObj[num]++;
is executed no matter what the result of the if condition is.在第二个代码中,您添加了else。
You're increasing
modeObj[num]++
outsideif
part of the conditional & the second code snippet. It should be like so instead: