Reputation: 13
I have a prob to solve, I have to use a loop to step through each position in an array of " winning numbers"to check whether the variable customer number (input from keyboard) matches any of the winning numbers. I must use a For loop to step through each position in the winning numbers array and to compare the customer number to each number the array contains. I cannot use any method to achieve this problem Thanks for your help! here what I did so far:
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");
}
Upvotes: 0
Views: 8162
Reputation: 7763
Below solution loops all the winning numbers and check for a match
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");
}
Upvotes: 2
Reputation: 133423
You should use indexOf()
to check whether customerNumbers
exists in winningNumbers
The
indexOf()
method returns the first index at which a given element can be found in the array, or -1 if it is not present.
Script
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");
}
Upvotes: 3