对于javascript,我有一个对象数组,我想查看用户的条目是否与数组中三个对象中任何一个的属性中的2个匹配。由于某种原因,我的“ for循环”仅适用于第一个对象,而从不检查其他两个对象。我该如何解决?
class Customer {
constructor(fN, lN, bal, cID, pass) {
this.firstName = fN;
this.lastName = lN;
this.balance = bal;
this.customerID = cID;
this.password = pass;
}
}
const bankers = [];
bankers.push(new Customer("Jack", "Scott", 3689.21, "4552", "2811"));
bankers.push(new Customer("John", "Smith", 2500.00, "4553", "1234"));
bankers.push(new Customer("Albert", "Price", 100000.00, "4554", "6189"));
let userID = prompt(`Please enter your customer ID.`);
let userPass = prompt(`Please enter your password.`);
for (let i = 0; i < bankers.length; i++) {
if (bankers[i].customerID === userID && bankers[i].password === userPass) {
console.log('Yay'); break;
} else {
console.log('boo'); break;
}
}
仅当我为第一个客户进行测试时,我的“ for循环”才有效。如果我尝试输入其他两个的客户ID或密码,它将失败。为什么会这样呢?我认为i
变量应该遍历所有3个对象
答案 0 :(得分:2)
两件事-一,您在Jack
前面缺少引号。第二,您需要在每次循环运行时重新定义变量-将userID
和userPass
声明移到循环内
class Customer {
constructor(fN, lN, bal, cID, pass) {
this.firstName = fN;
this.lastName = lN;
this.balance = bal;
this.customerID = cID;
this.password = pass;
}
}
const bankers = [];
bankers.push(new Customer("Jack", "Scott", 3689.21, "4552", "2811"));
bankers.push(new Customer("John", "Smith", 2500.00, "4553", "1234"));
bankers.push(new Customer("Albert", "Price", 100000.00, "4554", "6189"));
for (let i = 0; i < bankers.length; i++) {
let userID = prompt(`Please enter your customer ID.`);
let userPass = prompt(`Please enter your password.`);
if (bankers[i].customerID === userID && bankers[i].password === userPass) {
console.log('Yay');
} else {
console.log('boo');
}
}
根据评论,我相信您想像这样使用some
:
class Customer {
constructor(fN, lN, bal, cID, pass) {
this.firstName = fN;
this.lastName = lN;
this.balance = bal;
this.customerID = cID;
this.password = pass;
}
}
const bankers = [];
bankers.push(new Customer("Jack", "Scott", 3689.21, "4552", "2811"));
bankers.push(new Customer("John", "Smith", 2500.00, "4553", "1234"));
bankers.push(new Customer("Albert", "Price", 100000.00, "4554", "6189"));
let userID = prompt(`Please enter your customer ID.`);
let userPass = prompt(`Please enter your password.`);
if (bankers.some(banker => banker.customerID == userID && banker.password == userPass)) {
console.log('Yay');
} else {
console.log('boo');
}