2014-04-13 6 views
0

여러 개의 카운터를 포함하는 배열을 가지고 있으며 문자열을 통해 액세스했습니다. 즉 counters[div_block_id+'counter']이고 처음에는 각 카운터에 0 값을 할당하지만 일단 div를 클릭하면 카운터는 숫자가 아닌 값을 반환합니다. 배열 및 내용의 초기화.배열이 NaN을 반환합니다

var counters = new Array(); 
// Searches for every div that have an id attribute 
$('div').each(function() { 
    if (!this.id) {} else { 
     var id = this.id + '_counter'; 
     counters.push(id); //add id to counters array 
     counters[id] = 0; //initialize as 0 the counter of corresponding id 
     console.log(counters); //Logs the array 
    } 
}); 

당신은 샘플 here

답변

1

난 당신이 자바 스크립트의 배열과 객체를 혼동 생각을 볼 수 있습니다. 배열은 숫자 인덱스에만 기반합니다. 예를 들어 함수가 처음 실행될 때 배열은 다음과 같이 나타납니다.

counters.push(id); // your array will be counters[0] = id; 
counters[id] = 0; // nothing will happen because it's an invalid index 

키와 값을 저장하려면 객체를 사용해야합니다. 예 :

var counters = {}; // short code for object 
// Searches for every div that have an id attribute 
$('div').each(function() { 
    if (!this.id) {} else { 
     var id = this.id + '_counter'; 
     counters[id] = 0; //initialize as 0 the counter of corresponding id 
     console.log(counters[id]); //Logs the array 
    } 
}); 

희망이 있습니다.

+0

여전히 NaN이 반환되지만,이 점에 대해 설명 할 때 매우 유용합니다. – Ch32k0

+0

오류가 발생한 코드에 다른 것이 없으면 안됩니다. 이 예제를 확인할 수 있습니다. http://jsfiddle.net/gJAL3/ – NoGray

+0

아, 처음에는 괜찮습니다.하지만 onclick이 발생하면 NaN이 반환합니다. 질문에서 js 바이올린을 확인해주세요, 감사합니다! – Ch32k0

관련 문제