数组和for循环的困难

时间:2014-03-25 18:32:10

标签: javascript

我对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);
}

2 个答案:

答案 0 :(得分:2)

如果我理解正确:

替换此行:

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++) {

再试一次。

答案 1 :(得分:0)

first_name && last_name是有条件的。我相信你打算将它作为字符串连接。

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