Reputation: 219
When I run this, it claims x is undefined on the on the line with the for loop.
Full code:
function getCustomerNumbers() {
var customerNumbers = [];
customerNumbers.push(12, 17, 24, 37, 38, 43);
return customerNumbers;
}
function getWinningNumbers() {
var winningNumbers = [];
winningNumbers.push(12, 17, 24, 37, 38, 43);
return winningNumbers;
}
function checkNumbers(x, y) {
var matches = 0;
for (i=0; i<x.length; i++) {
for (j=0; j<y.length; j++) {
if (x[i] == y[j]) {
matches++;
}
}
}
return matches;
}
function displayResult() {
checkNumbers(getWinningNumbers(), getCustomerNumbers())
alert("This Week's Winning Numbers are:\n\n" + getWinningNumbers().toString() +
"\n\nThe Customer's Number is:\n\n" + getCustomerNumbers().toString() + "\n\nNumber of Matches:" + checkNumbers());
}
function init() {
displayResult();
}
window.onload = init;
Later it runs, with arrays going into values x and y. It ran fine when it was just x as an array and one for loop.
Anyone know what is wrong here?
Upvotes: 0
Views: 188
Reputation: 136074
You're calling checkNumbers
twice - the first time passing in valid values for x
& y
and the second time passing in nothing
function displayResult() {
// Good, but ignores result
checkNumbers(getWinningNumbers(), getCustomerNumbers())
//Nothing passed in
alert("This Week's Winning Numbers are:\n\n" + getWinningNumbers().toString() +
"\n\nThe Customer's Number is:\n\n" + getCustomerNumbers().toString() + "\n\nNumber of Matches:" + checkNumbers());
}
Upvotes: 0
Reputation: 8475
Your posted code is still missing something, as the first function
is missing.
The next thing I found was the second call to checkNumbers
doesn't pass anything in.
function displayResult() {
checkNumbers(getWinningNumbers(), getCustomerNumbers())
alert("This Week's Winning Numbers are:\n\n" + getWinningNumbers().toString() +
"\n\nThe Customer's Number is:\n\n" + getCustomerNumbers().toString() + "\n\nNumber of Matches:" + checkNumbers()); //<-- where are the parameters?
}
Working code:
function getCustomerNumbers(){
var customerNumbers = [];
customerNumbers.push(12, 17, 24, 37, 38, 43);
return customerNumbers;
}
function getWinningNumbers() {
var winningNumbers = [];
winningNumbers.push(12, 17, 24, 37, 38, 43);
return winningNumbers;
}
function checkNumbers(x, y) {
var matches = 0;
for (var i=0; i<x.length; i++) {
for (var j=0; j<y.length; j++) {
if (x[i] == y[j]) {
matches++;
}
}
}
return matches;
}
function displayResult() {
alert("This Week's Winning Numbers are:\n\n" + getWinningNumbers().toString() +
"\n\nThe Customer's Number is:\n\n" + getCustomerNumbers().toString() + "\n\nNumber of Matches:" + checkNumbers(getWinningNumbers(), getCustomerNumbers())
);
}
displayResult();
Upvotes: 2