gpt4 book ai didi

javascript - 嵌套 for 循环中具有 undefined variable 的函数

转载 作者:行者123 更新时间:2023-12-02 16:28:53 26 4
gpt4 key购买 nike

当我运行这个程序时,它声称 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 作为一个数组和一个 for 循环时,它运行得很好。

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

最佳答案

您发布的代码仍然缺少某些内容,因为缺少第一个 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();

关于javascript - 嵌套 for 循环中具有 undefined variable 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28482501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com