2013-10-31 2 views
0

문제는 배열에 텍스트가 추가되지 않고 있다는 것입니다. 코드는 괜찮아 보이지만 array.length를 인쇄하면 추가되지 않는다는 것을 확인할 수 있습니다.자바 스크립트 : 배열에 텍스트를 추가하지 못했습니다.

<script> 
    function addradio(value) 
    { 
     var element = document.createElement("input"); 
     var label = document.createElement("label"); 
     var tele = document.getElementById("Telephone"); 
     var selected_text = tele.options[tele.selectedIndex].innerHTML; 

     // Array uses to stop duplicate radio button 
     var countryArray = new Array(); 

     // Used to check if country is already in array, defaults to false 
     var contain = new Boolean(); 

     // Checks if text contains a "1", returns "-1" if it doesn't 
     var str = selected_text.indexOf("1"); 

     // For loop to check if country name is already in the array 
     for(var i = 0; i <= countryArray.length; i++) 
     { 
      if(countryArray[i] == selected_text) 
       contain = true; 
      else 
       contain = false; 
     } 

     // If value is not empty and text does not contain a "1" and array doesn't contain specified country 
     if(value != "" && str == "-1" && contain == false) 
     { 
      // Creating the attributes for a radio button 
      element.setAttribute("type", "radio"); 
      element.setAttribute("value", value); 
      element.setAttribute("name", "telephone"); 
      label.appendChild(element); 
      label.innerHTML += selected_text + "<br>"; 

      // Creating the radio button 
      var newradio = document.getElementById("fillme"); 
      newradio.appendChild(label); 

      // Adds country into the array if its' not already there 
      countryArray.push(selected_text); 
     } 
    } 
</script> 

누구나 내 Array.push() 함수로 문제를 식별 할 수 있습니까?

+0

'내가 <= countryArray.length'가

for(var i = 0; i <= countryArray.length; i++) { if(countryArray[i] == selected_text) contain = true; else contain = false; } 

나는이 쉽게 찾을 수 잘못된 조건. –

답변

1

빈 배열을 만든 다음 루프를 반복합니다. 비어 있기 때문에 길이가 없으므로 루프가 실행되지 않습니다. 결국 당신은 배열로 값을 밀어 넣지 만, 다음 번에 메서드를 실행하면 배열이 다시 비어있는 채로 시작합니다.

동일한 배열을 사용하고이 함수를 여러 번 호출하려고합니다.이 경우 여러 번 선언해야합니다 함수 밖의 배열.

또한 for 루프를 없애고 indexOf()을 사용하여 원하는 값이 배열에 있는지 확인할 수 있습니다.

 // Move this outside function 
    var countryArray = new Array(); 
    /* shorter syntax*/ 
    var countryArray =[]; 
    function addradio(value)... 
+0

감사합니다. 다시 한번 나는 실수하지 않고 그 실수를 저질렀다. 또한 for 대신 indexOf()를 사용하는 팁이 코드 리팩터링에 유용했습니다. – masterx

0

for 루프가 잘못되었습니다. 배열의 마지막 요소가 없습니다. 대신 일을

 // For loop to check if country name is already in the array 
     for(var i = 0; i < countryArray.length; i++) 
     { 
      if(countryArray[i] == selected_text) 
       contain = true; 
      else 
       contain = false; 
     } 
0

다음은 : 그러니까 기본적으로

if(!!countryArray.indexOf(selected_text) && countryArray.indexOf(selected_text) > -1) 
    { 
     //then item exist in array. You do not have to use the base bool operator, but secondary check. 
    } 

:

if(countryArra.indexOf(selected_text) > -1) 
    { 
    //it exist! 
    }