对于 javascript,我有一个对象数组,我想查看用户的条目是否与数组中三个对象中任何一个的属性相匹配。由于某种原因,我的“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 个对象
最佳答案
有两件事 - 第一,你漏掉了 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');
}
关于javascript - 循环不会搜索整个对象数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55034796/