当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript indexOf cannot check the same numbers in an array

问题描述:

var number = new Array();

number[1] = document.getElementById("num1");

number[1].addEventListener("change",function() { getNumbers(0); },false);

number[2] = document.getElementById("num2");

number[2].addEventListener("change",function() { getNumbers(1); },false);

number[3] = document.getElementById("num3");

number[3].addEventListener("change",function() { getNumbers(2); },false);

number[4] = document.getElementById("num4");

number[4].addEventListener("change",function() { getNumbers(3); },false);

number[5] = document.getElementById("num5");

number[5].addEventListener("change",function() { getNumbers(4); },false);

number[6] = document.getElementById("num6");

number[6].addEventListener("change",function() { getNumbers(5); },false);

function getNumbers(num) {

myNumbers[num] = parseInt(number[num+1].value);

if(!validNumber(myNumbers[num])) {

number[num+1].value="";

myNumbers[num]="";

}

}

function checkNums(Lotto, num) {

x=Lotto.indexOf(num);

if (x!=-1) {

return true;

}

return false;

}

var myNumbers = new Array();

function validNumber(num) {

if(checkNums(myNumbers, myNumbers[num])) {

alert("Number already chosen. Please enter a valid number between 1 and 45");

return false;

}

When i input a number into the array it keep alert the message "Number already chosen. Please enter a valid number between 1 and 45".

I want to ask about if I input a number into myNumber[0],and I call the checkNums function, it will detect the number i input into the myNumber[0] is in the myNumber array already and keep alert the message?

网友答案:

Check if the number is already in the array before you insert it. So, for example:

function getNumbers(num) {
   var newNumber = parseInt(number[num+1].value, 10);  // Note: it might be worth 
                                                       // checking for NaN here as well
   if (myNumbers.indexOf(newNumber) != -1) {
       myNumbers[num] = newNumber;
   }
   else {
       alert("Number already chosen. Please enter a valid number between 1 and 45");
       number[num+1].value="";
   }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: