gpt4 book ai didi

javascript - 数组和for循环的困难

转载 作者:行者123 更新时间:2023-11-30 17:32:49 25 4
gpt4 key购买 nike

我在使用 for 循环时遇到困难。学生的名字和姓氏的第一个实例有效,但其余姓名将获得 alert。任何帮助表示赞赏。谢谢。

html:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Js Test</title>
</head>
<body>
<input type="name" id="first_name" placeholder="First Name"/>
<input type="name" id="last_name" placeholder="Last Name"/>
<input type="name" id="result" placeholder="Full Name"/>
<button onclick='validator()' id="submit">Submit</button>
</body>
</html>

js:

var students = [
{first:'Max', last:'Smith'},
{first:'Ardon', last:'Bailey'},
{first:'Todd', last:'Gumke'},
{first:'Bob', last:'Plug'},
{first:'Trub', last:'Lee'}];

function full_name (first_name, last_name) {
var foo = false;
for (var i = 0; i < students.length; i++) {
if (students[i].first === first_name && students[i].last === last_name) {
foo = true;
}
}
if (foo === true) {
alert('yay');
} else {
alert('sad');
}
}


function validator() {
var result = document.getElementById('result');
result.value = full_name(document.getElementById('first_name').value, document.getElementById('last_name').value);
}

最佳答案

如果我理解正确的话:

替换这一行:

if ((first_name && last_name) === (students_first[i] && students_last[i])){

用这个:

if (first_name == students_first[i] && last_name == students_last[i]){

还有这一行:

for(i = 0; i < (students_first && students_last.length); i++) {

用这个:

for(i = 0; i < students_first.length && i < students_last.length; i++) {

再试一次。

关于javascript - 数组和for循环的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22643356/

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