繁体   English   中英

此JavaScript代码(数组)有什么问题?

[英]What's wrong with this JavaScript Code (Arrays)?

下面是一个代码片段,它找出“数组的每个元素重复多少次”。 一切都按预期进行,但不会给我“ ebay重复次数”

var strArr = ["google","ebay","yahoo","google","ebay","facebook","facebook","google"];
var output= {};
strArr.forEach(function(element) {
    var count = 0;
    try{
        while(strArr.indexOf(element) !== -1){
            strArr.splice(strArr.indexOf(element),1);
            count++;

        }  
    }catch(e){
        console.log(e);
    }
 output[element] = count;
});
console.log(output);

我尝试使用debugger; ,我发现数组的第二个元素被跳过了。

预期产量:

google:3
ebay:2
yahoo:1
facebook:2

实际输出:

google:3
yahoo:1
facebook:2
  • ForEach从索引0获取Google:
  • 您从列表中删除了Google(包括零)
  • ForEach移至索引1,随着ebay移至索引0,该索引现在具有Yahoo

对不起英语不好

首先,您不应该在遍历数组时更改数组(如ChrisG在评论中提到的那样),其次,实际上不需要循环。 使用reduce代替

 let strArr = ["google", "ebay", "yahoo", "google", "ebay", "facebook", "facebook", "google"]; let res = strArr.reduce(function(a, b) { a[b] = (a[b] || 0) + 1; return a; }, {}); console.log(res); 

可以使用一个简单的循环来代替使用reduce:

let strArr = ["google", "ebay", "yahoo", "google", "ebay", "facebook", "facebook", "google"];
let output = {};
strArr.forEach(function(val) {
  output[val] = output[val] || 0;
  output[val]++;
});

console.log(output);

您可以通过将结果记录到循环中来轻松地注意到问题:

 var strArr = ["google","ebay","yahoo","google","ebay","facebook","facebook","google"]; var output= {}; strArr.forEach(function(element) { var count = 0; while(strArr.indexOf(element) !== -1){ strArr.splice(strArr.indexOf(element),1); count++; console.log(element, count, JSON.stringify(strArr)); // <-- added this line } output[element] = count; }); console.log(output); 

如您所见,在删除第一项“ google”之后,第二项不是ebay,而是yahoo!。 删除yahoo之后,下一项不是ebay,而是facebook,并且数组中留有[“ ebay”,“ ebay”]。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM