gpt4 book ai didi

javascript - For 与 For Each 循环行为 - JavaScript

转载 作者:行者123 更新时间:2023-11-28 13:20:39 24 4
gpt4 key购买 nike

我在谷歌上搜索寻找一个能够检测数组中元素重复出现的函数。我找到了以下解决方案:

var arr = ["dog","dog","cat","lion","dog","cat" ]
arr.forEach(function(x) {
counts[x]= (counts[x] || 0)+1
});
console.log(counts);

上述的输出是:

 Object {dog: 3, cat: 2, lion: 1}

当使用简单的FOR循环时:

for(var x=0; x<arr.length; x++){
counts[x]= (counts[x] || 0)+1
}
console.log(counts);

上述的输出是:

Object {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}

问题:

首先,我不完全明白这里发生了什么:

counts[x]= (counts[x] || 0)+1

其次,在 ForEach 循环中它如何能够检测元素的重复出现?这已经内置了吗?

在下面的代码中,属性名称dog、cat和lion仅出现一次。

Object {dog: 3, cat: 2, lion: 1}

这里,数组中每个项目的属性名称单独显示。

Object {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}

也许我不明白 ForEach 循环是如何工作的,但为什么两个循环的行为不同? foreach 循环似乎检测到重复的属性名称?

最佳答案

您提出了两个不同的问题:

  • 为什么使用 forArray#forEach 会得到不同的结果?

  • counts[x]= (counts[x] || 0)+1 是如何工作的?

为什么使用 forArray#forEach 会得到不同的结果?

Alexander has answered the first one ,但为了完整起见,这是因为 for 循环中的 x 是该循环迭代的 key (索引)(012 等);但 Array#forEach 回调中的 x 是该循环迭代的("dog"“狗”“猫” 等等)。

假设是一个非稀疏数组,for 相当于

theArray.forEach(function(value) {
// ...do something with value
});

var index, value;
for (index = 0; index < theArray.length; ++index) {
value = theArray[index];
// ...do something with value
}

...当然,在 for 示例中,我们声明了两个在 forEach 示例中未声明的变量。

对于您正在做的事情,您需要的是,而不是索引,因此如果您想使用for循环,则应该是:

var x;
for(var index=0; index<arr.length; index++){
x = arr[index];
counts[x]= (counts[x] || 0)+1
}
console.log(counts);

counts[x]= (counts[x] || 0)+1 是如何工作的?

您尚未展示 counts 是如何初始化的,但我假设它是

var counts = {};

var counts = []; // (This would mostly be wrong, but it works)

这意味着,如果x“dog”counts[x]将为未定义,因为 counts 一开始并没有一个名为 dog 的属性。然后你这样做:

counts[x]= (counts[x] || 0)+1

...这是

counts[x]= (counts["dog"] || 0)+1

...这是

counts[x]= (undefined || 0)+1

JavaScript 的 || 运算符是 curiously powerful :它评估左侧,如果这是“真实的”,则将左侧作为结果;如果左侧为“假”,则运算符评估右侧并将其作为结果。 “真实”值是所有不“虚假”的值; “falsey”值为 undefinednull0""NaN >,当然还有false

这意味着未定义|| 00,因为 undefined 是 falsey,我们有:

counts[x]= (0)+1

...这是

counts[x]= 1

现在,counts[x](其中x“dog”)包含1

下次当你对x = "dog"这样做时,你就拥有了

counts[x]= (counts[x] || 0)+1

...这是

counts[x]= (counts["dog"] || 0)+1

...这是

counts[x]= (1 || 0)+1

由于 1真实1 || 01,所以我们有:

counts[x]= (1)+1

...这是

counts[x]= 2

这样继续下去,因此它会计算您在数组中看到 "dog" 的次数(以及 "cat""lion" 等)。

关于javascript - For 与 For Each 循环行为 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33409874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com