2015-02-24 82 views
-1
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; 
} 

當我向數組中輸入一個數字時,它會一直提醒「數字已被選中,請輸入1到45之間的有效數字」。javascript indexOf不能檢查數組中的相同數字

我想請教一下,如果我輸入一個數字mynumber的[0],我叫checkNums功能,它會檢測編號i輸入到mynumber的[0]是mynumber的數組中已經並保持警戒信息?

+0

你的意思是你設置通過myNumbers [0] = 10,然後再次調用該函數?它當然會警覺。 – Kai 2015-02-24 17:46:00

+0

那麼如何使用checkNum函數檢查數組中已經存在的數字而不檢查輸入的數字呢? – 2015-02-24 17:50:31

+1

@TanYunShen:檢查數字是否在數組* *中,然後只在它不在*時插入*。 – 2015-02-24 17:56:29

回答

0

檢查數字是否已經在之前插入。因此,舉例來說:

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=""; 
    } 
} 
相關問題