gpt4 book ai didi

javascript - 使用数组查找匹配项的“For”循环不执行

转载 作者:行者123 更新时间:2023-12-01 01:56:53 25 4
gpt4 key购买 nike

我正在尝试创建一个多项选择测验,然后将给出的答案与其他答案进行比较(仅以数组形式给出)。测验有效并且返回了值,但最后的“for”循环似乎被程序忽略了。我在想问题可能出在执行顺序上,我想也许将 script 标记放在 HTML 末尾会有所帮助,但事实并非如此。然后我认为问题出在函数本地声明的变量中,所以我在外部声明它们。依然没有。请透露一些信息。代码已更改为更短。

var userDrinkAnswer;

function submitDrinkAnswer() { // func is called from HTML
for (...) {
userDrinkAnswer = radiosDrink[i].value;
}
return userDrinkAnswer;
}

//same with userApologyAnswer;
//same with userPlaceAnswer;

let myAnswers = ['Tea', 'Massage', 'Zoo'];
let hisAnswers = [userDrinkAnswer, userApologyAnswer,userPlaceAnswer];

function findMatch() {
for (let myAnswersIndex = 0; myAnswersIndex < myAnswers.length; myAnswersIndex++) {
for (let hisAnswersIndex = 0; hisAnswersIndex < hisAnswers.length; hisAnswersIndex++) {
if (myAnswers[myAnswersIndex] === hisAnswers[hisAnswersIndex]) {
document.write(myAnswers[myAnswersIndex]);
}
}
}
}

findMatch();

最佳答案

试试这个。我只是简化了它。

注意:不要使用document.write,因为它会在每次调用时替换整个 html。

let userDrinkAnswer='Tea', userApologyAnswer='Massage', userPlaceAnswer = 'Zoo';
let myAnswers = ['Tea', 'Massage', 'Zoo'];
let hisAnswers = [userDrinkAnswer, userApologyAnswer, userPlaceAnswer];

function findMatch() {
myAnswers.forEach(function(elem, index){
console.log(elem===hisAnswers[index]);
});
}

findMatch();

关于javascript - 使用数组查找匹配项的“For”循环不执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50955270/

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