2016-12-26 58 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]也帮助我更好地理解这个关键字 –