2016-12-26 83 views
1

代碼:需要幫助理解使用關聯數組來跟蹤數組值出場

method = function(a) { 
//use associative array to keep track of the total number of appearances of a value 
//in the array 
var counts = []; 
for(var i = 0; i <= a.length; i++) { 
    if(counts[a[i]] === undefined) { 
    //if the condition is looking for a[0],a[1],a[2],a[3],a[4],a[5] inside counts[] one value at a time and does not find them inside counts[] it will set each value to 1 

    counts[a[i]] = 1; 
    console.log(counts[a[i]]); 
    } else { 
     return true; 
    } 
} 
return false; 
} 

JS的控制檯日誌1X6

哪有條件看裏面計數的值[A [1] ]如果所有計數[a [i]]值都被設置爲1,每次迭代都會重複?難道它總是比較1比1嗎?例如,如果一個數組是[1,2,3,4,5,2]並且計數[a [1]](數組中的第一個int 2)未定義,然後設置爲1,那麼如何將數組[條件是否知道count [a [5]](數組中的第二個int 2)與counts [a [1]]的值相同,因此它應該返回true?或許我誤解了正在發生的事情。 我將不勝感激任何幫助。感謝

+0

原因計數會[2]將是1,而不是不確定返回true ... –

+0

這是沒有什麼可以解釋的,問題是你沒有得到邏輯... –

回答

1
function counter(){ 
this.counts=[]; 
} 

counter.prototype.add=function(a){ 
    if(this.counts[a] === undefined) { 
    this.counts[a] = 1; 
    console.log(this.counts); 
    } else { 
     return true; 
    } 
    return false; 
} 

試試這個:

c= new counter(); 
c.counts;//[] 
c.add(1); 
c.counts;//[ ,1] 
c.add(5); 
c.counts;//[ ,1, , , ,1] 
c.add(1);//true 
... 

它可以幫助你瞭解什麼在

+0

天才!你的例子確實有幫助。改變了本地變量,並能夠看到值進入計數變種。 [1:1] [1:1,2:1] [1:1,2:1,3:1] [1:1,2:1,3:1,4:1] [1 :1,2:1,3:1,4:1,5:1]也幫助我更好地理解這個關鍵字 –