如何使用布尔值检查for循环中是否正确满足条件?

时间:2019-06-07 15:44:54

标签: javascript arrays object boolean

我希望出现一条提示消息,要求用户输入学生姓名。 Javascript将浏览单独的JS文件中的学生记录,然后在message变量中输出学生的信息。

以下是相关的javascript代码:

var students=[
    {
        name:'Chris',
        track:'IOS',
        achievements:'100',
        points:'1000'
    },
    {
        name:'John',
        track:'Web Design',
        achievements:'90',
        points:'1000'
    },
    {
        name:'Brent',
        track:'Front-End',
        achievements:'70',
        points:'1000'
    },
    {
        name:'Josh',
        track:'Full-Stack',
        achievements:80,
        points:'1000'
    },
    {
        name:'Nick',
        track:'AI',
        achievements:'60',
        points:'1000'
    }
];

function print(message) {
    document.write(message);
}
var message="";
var flag=false;
var search=prompt("Type name of student. Type 'quit' to exit.");
while (search!=="quit") {
    for (var i=0; i<students.length; i+=1) {
    var studentName=students[i].name;
        if (studentName===search) {
            flag=true;
            break;
        } 
    }
    if (flag) {
        message+="<h1>"+studentName+"</h1>";
        message+="<p>"+students[i].track+"</p>";
        message+="<p>"+students[i].achievements+"</p>";
        message+="<p>"+students[i].points+"</p>";
    } else {
        alert("That student does not exist. Try again");
        search=prompt("Type name of student");
    }
}
print(message);

我意识到我已经接近了,但是我的一个问题是,我尝试从for循环中访问的任何变量将仅在该循环中是本地的。那么,如果我无法在条件语句中访问局部for循环变量,那么if和else条件将如何工作?我只是希望它找到一个匹配项,一旦匹配,停止for循环,然后继续使用该特定元素索引。

2 个答案:

答案 0 :(得分:0)

我将放弃循环并改用find()。这将返回找到的学生对象,或者如果找不到该学生,它将返回--with-password-argon2

undefined

然后我们可以将代码放入递归函数中,该函数将不断调用自身,直到用户找到学生或输入let student = students.find(s => s.name == search)

quit

答案 1 :(得分:0)

怎么样?

var students = [...];

function format(student) {
  return (
    '<h1>' + student.name + '</h1>' +
    '<p>' + student.track + '</p>' +
    '<p>' + student.achievements + '</p>' +
    '<p>' + student.points + '</p>'
  );
}

function lookup(name) {
  return students.find(function(student) {
    return name === student.name
  });
}

function print(message) {
  document.write(message);
}

function searchPrompt() {
  return prompt("Type name of student. Type 'quit' to exit.");
}

function run() {
  var search = searchPrompt();

  if (search === 'quit') {
    return;
  }

  var student = lookup(search);

  if (student) {
    print(format(student));
  } else {
    alert("That student does not exist. Try again");
    run();
  }
}

run();