所以我有一个登录表单,我想检查输入的名称和密码是否已存在于 JSON 对象中,这两种情况都会提示不同的消息,但问题是它做得不对,这是代码为了更清楚:
function registerInfo(){
var name = document.forms[0].username.value;
var pw = document.forms[0].pw.value
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (name === "" || pw === "") {
alert ('please complete all the forms')
}
for (var i = 0; i < response.loginfo.length; i++){
if ( name === response.loginfo[i].username && pw ===
response.loginfo[i].password) {
alert('Welcome back ' + name);
break;
} // if statement curly braces
} // loop curcly braces
for (var i = 0; i < response.loginfo.length; i++){
if ( name != response.loginfo[i].username && pw != response.loginfo[i].pw){
alert('Welcome here new ');
break;
} // if statement curcly braces
} // for
} // ready state if statement curly braces
} // function curly braces
xhttp.open("GET", "login.json", true);
xhttp.send();
return false;
}
这是用于快速测试的 JSON 对象
{
"loginfo" : [
{
"username" : "moh",
"password" : "lol"
},
{
"username" : "zaki",
"password" : "123"
}
]
}
问题是当用户输入 JSON 对象 id 中存在的用户名和密码时,确实会发出警报“欢迎回来!” ,还有“欢迎新人”,我不想这样做,因为最新的警报是针对新用户的,他们的凭据不存在于 JSON 对象中。
最佳答案
最简单的修复是不允许执行第二个 for 循环,如果找到匹配项,那么
如果找到匹配,则设置一个标志,如果设置了该标志,则不执行第二个 for 循环。
Return
而不是从第一个 for 循环中中断。
但是,您可以通过使用 Array.prototype.some
检查是否有任何值匹配来减少代码的冗长
var hasMatch = response.loginfo.some( s => s.username === name && s.password === pw );
hasMatch
如果找到匹配则返回 true
alert( "Welcome " + (hasMatch ? "back" + name : "here new" ) );
关于Javascript 循环通过 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49917553/