For Loop in JavaScript - Lottery Website

后端 未结 2 1764
余生分开走
余生分开走 2021-01-24 03:35

I am trying to turn this code into a correct for loop statement, so that I can save my repetitions. I have tried my best to get it done, but I just don\'t know how I can write i

相关标签:
2条回答
  • 2021-01-24 04:24

    try something like this:

    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");
    }
    
    0 讨论(0)
  • 2021-01-24 04:28

    Here's an example without using array. Input check was added.

    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!');
        }
    }
    
    0 讨论(0)
提交回复
热议问题