为什么这种用于计算数组重复并将其存储到对象中的方法有效

Why does this method for counting duplicates of an array and storing it into an object work?

本文关键字:存储 对象 有效 方法 用于 计算 数组 为什么      更新时间:2023-09-26
var counts = {};
var your_array = ['a', 'a', 'b', 'c'];
your_array.forEach(function(x) { 
  counts[x] = (counts[x] || 0) + 1; 
});
console.log(your_array);

在javascript中,为什么你必须做counts[x] = (counts[x] || 0) + 1;为什么counts[x] += 1;不起作用?

这将输出{ a: 2, b: 1, c: 1},但为什么呢?

如果counts[x] undefined,问题就出现了。在这种情况下,增量不起作用。逻辑"or"||)计算左侧的值,如果该值是假的,则取右部分。

例如,如果你把线分开,你会得到

counts[x] || 0

它返回counts[x]的真值,如果返回undefinedfalsenull,甚至返回0则返回值为0的右部分。

添加和分配应明确。

直接来自 MDN:

在 JavaScript 中,真值是在布尔上下文中评估时转换为 true 的值。所有值都是真值,除非它们被定义为假值(即,除了false0""nullundefinedNaN)。