簡體   English   中英

使用for循環比較數組中的數字

[英]Compare numbers in Array using for loop

我有一個要解決的問題,我必須使用循環來遍歷“中獎號碼”數組中的每個位置,以檢查可變客戶號碼(從鍵盤輸入)是否與任何中獎號碼匹配。 我必須使用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");
}

您應該使用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");
}

下面的解決方案循環所有中獎號碼並檢查是否匹配

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM