2011-08-31 6 views
0
<div class="aa"> 
    <input type='radio' id="1" name='choices' value='1'/> 
    <input type='radio' id ="2" name='choices' value='2'/> 

    <input type='radio' id="3" name='choices1' value='3'/> 
    <input type='radio' id="4" name='choices1' value='4'/> 
</div> 

jQuery를길이가 정의되지 않은 이유는 무엇입니까?

$(".aa :radio").change(function() { 

    var names = {}; 
    $('.aa :radio').each(function() { // find unique names 
    names[$(this).attr('name')] = true; 
    }); 
    var count = 0; 
    $.each(names, function() { // then count them 
    count++; 
    }); 
    alert ("count " + count + " length " + names.length); //names length comes up as undefined why? 
}).change(); 
+3

자바 스크립트 객체는 length 속성이없는 –

답변

4

namesobject가 아닌 array 때문이다. 귀하의 예제에서 count는 객체 이름에있는 키의 길이입니다. 자바 스크립트 객체의 길이 속성이없는

var count = 0; 
for(var i in names) { 
    count++; 
} 
count; // length 

또는 최신 브라우저 Object.keys(names).length

+3

당신은'hasOwnProperty'에 대해 잊어 버렸습니다 ... –

0

:

은 키의 길이를 얻으려면. 배열 만 할 수 있습니다.

개체에있는 키 수를 알고 싶으면 루프를 반복해야합니다. 이 질문에 대한 답을 체크 아웃 : http://stackoverflow.com/questions/5223/length-of-javascript-associative-array :

Length of a JavaScript object

관련 문제