我有一个包含客户列表的数组。我正在声明一个以客户名称作为参数的函数。我希望这个函数循环遍历数组以找出客户是否在数组中。
var customers = [
{fullName: 'Marshall Hathers',
dob: '01/07/1970'},
{fullName: 'Margaret May',
dob: '01/07/1980'}
];
功能:
function findCustomer(customer) {
for(i=0; i<customers.length; i++) {
var found;
if(customer === customers[i].fullName) {
found = true;
console.log('Customer has been found');
break;
} else {
found = false;
console.log('Customer has not been found');
break;
}
}
第一次找到客户时效果很好,但在尝试找到第二个客户时打印结果不正确。
有人可以帮忙吗?
最佳答案
所以看看你在循环中实际上说了什么。循环体将为每个客户运行。所以你是说
For the first customer in the array
if this is my customer
print "found" and stop looping
otherwise
print "not found" and stop looping
您觉得这样合适吗?仅查看第一条记录是否真的可以告诉您未找到该客户?
请注意,由于所有可能性都以“并停止循环”结束,因此永远不会检查第二条记录。循环的要点在于,至少在某些情况下,您不会停止循环,对吗?这样您就会看到第二个重复该步骤,依此类推...
关于Javascript - For 循环无法正确找到数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41958620/