Javascript - For Loop无法正确查找数组中的值

时间:2017-01-31 13:17:38

标签: 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;
         }
    }

第一次找到客户时效果很好,但在尝试查找第二个客户时打印错误。

有人可以帮忙吗?

6 个答案:

答案 0 :(得分:2)

那么看看你在循环中实际说的是什么。循环体将为每个客户运行。所以你要说

For the first customer in the array
    if this is my customer
        print "found" and stop looping
    otherwise
        print "not found" and stop looping

这看起来对你好吗?单独查看第一条记录是否真的告诉您没有找到客户?

请注意,由于所有可能性以“并停止循环”结束,因此永远不会检查第二条记录。循环的重点是,至少在某些条件下,你停止循环,对吗?这样你就可以看到为第二步重复的步骤,依此类推......

答案 1 :(得分:1)

忽略else部分,如果找到则打破for循环。

function findCustomer(customer) {
    var found, i;
    for (i = 0; i < customers.length; i++) {
        if (customer === customers[i].fullName) {
            found = true;
            console.log('Customer has been found');
            break;
        }
    }
    if (!found) {
        console.log('Customer has not been found');
    }
}

答案 2 :(得分:1)

使用Array.some prototype function查找元素

function findCustomer(customer) {
    var found = customers.some(function(item) {return item.fullName == customer;});
    console.log(found ? 'Customer has been found': 'Customer has not been found');
}

答案 3 :(得分:0)

当您的脚本达到休息时,您正在退出循环

因此,如果您寻找第二位客户,您将输入“其他”。那里你有一个退出循环的休息时间,所以你永远不会得到console.log

答案 4 :(得分:0)

我会改变这样的代码(按评论中的建议编辑)

&#13;
&#13;
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++) {
    if (customer === customers[i].fullName) {
      console.log('Customer has been found');
      return true;
    }
  }
  console.log('Customer has not been found');
  return false;
}

findCustomer('Marshall Haters');
&#13;
&#13;
&#13;

答案 5 :(得分:0)

删除休息时间;来自else块的声明; 在这里,我为你重写了这个功能。

function findCustomer(customer) {
var found = false; 
       for(i=0; i<customers.length; i++) {

          if(customer === customers[i].fullName) {
              found = true;              
              break;
          } else {
              found = false;
         }
    }

    if(found){
        console.log('Customer has been found');
    }else{
         console.log('Customer has not been found');
    }
}