gpt4 book ai didi

javascript - 得到一个未定义的返回值,尽管在函数中它不是

转载 作者:行者123 更新时间:2023-11-30 09:31:03 25 4
gpt4 key购买 nike

function getCheckedRadioButton() {
getRadioButtons().forEach(function (t) {
if (t.checked) {
console.log(t);
return t;
}
});
}

上面的函数被调用:

var x = getCheckedRadioButton();
console.log(x);
if (x.className)
{
//do something
}

控制台输出:

input type="radio" id="pvp" name="gameMode" value="0" class="hasTextboxes"
undefined
Uncaught TypeError: Cannot read property 'className' of undefined

我什至试过:

if (getCheckedRadioButton().className)

但它不起作用。

最佳答案

这一行:

return t;

正在从此函数返回:

function (t) {
//...
}

不是这个:

getCheckedRadioButton() {
//...
}

你到底想返回什么?只是数组中的第一个匹配结果?您可以只使用普通循环而不是带有嵌套函数的循环:

var radios = getRadioButtons();
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
console.log(radios[i]);
return radios[i];
}
}
// return some default if nothing is found?

关于javascript - 得到一个未定义的返回值,尽管在函数中它不是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46265497/

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