使用带 javascript 的逻辑运算符计算数组元素的出现次数,并将其存储在以数组项为键、频率为值的对象中

Count the Occurance of array elements Using Logical Operators with javascript and store it in a object with array items as key and frequency as value

例如,给定输入数组

const scored= ['Lewandowski'1, 'Gnarby'1, 'Lewandowski', 'Hummels'];

我们应该得到输出

{莱万多夫斯基:2,纳尔比:1,胡梅尔斯:1}

这应该只在逻辑运算符的帮助下完成。

让我们考虑数组

const scored= ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];

然后我们必须创建一个空对象

const scorers={};

现在遍历我们可以做的数组

for (const player of scored) {
  (scorers[player] += 1) || (scorers[player] === 1 || (scorers[player] = 1));
}

(scorers[player] += 1):-> 首先我们尝试添加假装“player”在 object.if player is there else 如果“player”是不在那里它将 return Nan 并继续下一个表达式 (scorers[player] === 1 || (scorers[player] = 1))。然后我们检查以下步骤。

scorers[player] === 1:-> 接下来如果玩家在场,我们检查值是否为 1,如果值为 1,则操作不会继续 further.if player has a value 1,表示他已经被分配了一个起始值。

scorers[player] = 1:-> player 没有 1 的值,我们给他赋值为 1 开始。

下面是最终代码的样子

 const scored = ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'];
const scorers = {};
for (const player of scored) {
   (scorers[player] += 1) || (scorers[player] === 1||(scorers[player]=1));
    }
console.log(scorers);