我正在构建一个javascript函数,该函数接收输入并针对数组中存储的对象检查输入,以查看其是否与任何
相匹配if else语句不起作用
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
它应该告诉用户用户名是否可用
答案 0 :(得分:0)
您的问题的直接答案是:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
您的代码中有一些错误,需要修复。
另外,请查看Array.prototype.find()
以获取更多信息。
希望这将帮助您朝正确的方向开始。祝你好运!
答案 1 :(得分:0)
最后了解我在做什么错,必须指向帐户匹配项以检查对象数组中包含的用户名
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login