Javascript - For 循环无法正确找到数组中的值

标签 javascript arrays

我有一个包含客户列表的数组。我正在声明一个以客户名称作为参数的函数。我希望这个函数循环遍历数组以找出客户是否在数组中。

    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/

相关文章:

javascript - scope.$observe 不是 AngularJS 指令中的函数

javascript - 只需要重置 Javascript 数组的索引

c++ - 对象数组的构造函数中的随机数

javascript - HTML:子节点知道它是哪个子节点

javascript - 提取函数体的正则表达式

javascript - 更改背景图像 css 导致添加额外的 div

javascript - 将 DOM 变量作为 props 传递给 Reactjs

Java-旋转数组

java - 连续数字的最大子数组

javascript - 包含对象数组和字符串数组的对象