在嵌套for循环中具有未定义变量的函数

时间:2015-02-12 16:21:26

标签: javascript arrays function for-loop

当我运行它时,声称x在for循环的行上未定义。

完整代码:

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;

稍后它运行,数组进入值x和y。当它只是x作为一个数组而一个用于循环时它运行正常。

有人知道这里有什么问题吗?

2 个答案:

答案 0 :(得分:2)

由于缺少第一个function,您发布的代码仍然缺少某些内容。

我发现的第二个问题是对checkNumbers的第二次调用没有传递任何内容。

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?
}

工作代码:

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();

答案 1 :(得分:0)

您正在拨打checkNumbers两次 - 第一次传递x&amp;的有效值y,第二次没有传递

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