簡體   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