2012-10-26 44 views
1

我想把這段代碼變成正確的循環語句,以便我可以保存我的重複。我已經盡了最大努力完成它,但我不知道我怎樣才能正確地寫:For循環在JavaScript - 彩票網站

function myProg() { 
    var luckyNumber = 3; 
    var luckyNumber2 = 5; 
    var luckyNumber3 = 8; 
    var firstInput = document.luckForm.numberBox.value; 
    var secondInput = document.luckForm.numberBox2.value; 
    var thirdInput = document.luckForm.numberBox3.value; 
    var temp = ''; 

    if (firstInput == luckyNumber && secondInput == luckyNumber2 && thirdInput == luckyNumber3 || firstInput == luckyNumber && secondInput == luckyNumber3 && thirdInput == luckyNumber2 || firstInput == luckyNumber2 && secondInput == luckyNumber3 && thirdInput == luckyNumber || firstInput == luckyNumber2 && secondInput == luckyNumber && thirdInput == luckyNumber3 || firstInput == luckyNumber3 && secondInput == luckyNumber && thirdInput == luckyNumber2 || firstInput == luckyNumber3 && secondInput == luckyNumber2 && thirdInput == luckyNumber) 
    { 
     alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!'); 
    } 
} 
+4

對數字和輸入使用數組而不是單獨的變量。 – Barmar

+0

哦,我不允許使用數組:(我必須使用最基本的JavaScript語句,並找出如何用循環進行總結。 –

+2

如果這是作業作業,我不確定這是哪個地方尋求幫助 - 我也認爲這聽起來像一個非常愚蠢的任務 – Cecchi

回答

0

嘗試這樣:

Array.prototype.getDuplicates = function() { 
    var cache = {}, results = [], that = this; 
    that.forEach(function(item, index) { 
     if(!cache.hasOwnProperty(item) && that.lastIndexOf(item) > index) { 
      results.push(item); 
     } 
     cache[item] = true; 
    }); 
    return results; 
} 

var answers = [luckyNumber, luckyNumber2, luckyNumber3]; 
var indexes = [answers.indexOf(firstInput), answers.indexOf(secondInput), answers.indexOf(thirdInput)]; 
if(indexes.indexOf(-1) === -1 && indexes.getDuplicates().length === 0) { 
    // alert("Whatever"); 
} 
+2

這將使'5 5 5'成爲一個有效的組合,我不認爲它是。 –

+0

我想到了,我現在就編輯它。 – Cecchi

0

這裏是不使用數組的例子。輸入檢查已添加。

function myProg() { 
    var numbersToMatch = 3; 
    var luckyNumbers = {n1: 3, n2: 5, n3: 8}; 
    var firstInput = parseInt(document.luckForm.numberBox.value); 
    var secondInput = parseInt(document.luckForm.numberBox2.value); 
    var thirdInput = parseInt(document.luckForm.numberBox3.value); 

    if (isNaN(firstInput) || isNaN(secondInput) || isNaN(thirdInput)) { 
     alert('All inputs must be numbers!'); 
     return; 
    } 

    var inputs = {n1: firstInput, n2: secondInput, n3: thirdInput}; 
    var matches = {n1: false, n2: false, n3: false}; 

    for (var i in inputs) { 
     for (var j in luckyNumbers) { 
      if ((!matches[j]) && (luckyNumbers[j] == inputs[i])) { 
       matches[j] = true; 
       numbersToMatch--; 
       break; 
      } 
     } 
    } 

    if (numbersToMatch == 0) { 
     alert('Congratulations! You got all 3 numbers correct. You\'ve won £1000!'); 
    } 
}