使用for循环比较Array中的数字

时间:2015-06-15 16:14:09

标签: javascript arrays loops

我有一个要解决的问题,我必须使用一个循环来逐步完成每个位置 一组“中奖号码”,用于检查可变客户号码(从键盘输入)是否与任何中奖号码匹配。 我必须使用For循环逐步遍历中奖号码数组中的每个位置,并将客户编号与数组包含的每个数字进行比较。 我不能用任何方法来实现这个问题 谢谢你的帮助!  这是我到目前为止所做的:

var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];    

for (var i = 0; i < winningNumbers.length; i++) {

    if (customerNumbers == 12 || //condition determinates the winning numbers
        customerNumbers == 17 ||
        customerNumbers == 24 ||
        customerNumbers == 37 ||
        customerNumbers == 38 ||
        customerNumbers == 43)
        alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
    alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}

2 个答案:

答案 0 :(得分:3)

您应该使用indexOf()来检查customerNumbers

中是否存在winningNumbers
  

indexOf()方法返回可在数组中找到给定元素的第一个索引,如果不存在则返回-1。

脚本

var customerNumbers=prompt("Enter your number:" );
var winningNumbers=[12, 17, 24, 37, 38, 43];
if (winningNumbers.indexOf(parseInt(customerNumbers, 10)) > -1) 
    alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"We have a match and a winner!");
} else {
    alert("This week Winning numbers are:"+"\n"+"\n"+winningNumbers+"\n"+"\n"+"The customer's Number is:"+"\n"+"\n"+customerNumbers+"\n"+"\n"+"Sorry you are not a winner this week");
}

答案 1 :(得分:1)

以下解决方案循环所有中奖号码并检查匹配

var customerNumbers = prompt("Enter your number:");
var winningNumbers = [12, 17, 24, 37, 38, 43];
var match = false;

for (var i = 0; i < winningNumbers.length && !match ; i++) {
  if (winningNumbers[i] == customerNumbers) {
    match = true;
  }
}

if (match)
  alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "We have a match and a winner!");
} else {
  alert("This week Winning numbers are:" + "\n" + "\n" + winningNumbers + "\n" + "\n" + "The customer's Number is:" + "\n" + "\n" + customerNumbers + "\n" + "\n" + "Sorry you are not a winner this week");
}