繁体   English   中英

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

[英]Javascript - For Loop not finding values in array correctly

我有一个包含客户列表的数组。 我在声明一个以客户名称为参数的函数。 我希望此函数在数组中循环查找客户是否在数组中。

    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

您觉得合适吗? 仅查看第一条记录是否真的告诉您找不到客户?

请注意,由于所有可能性都以“并停止循环”结尾,因此永远不会检查第二条记录。 循环的全部意义在于,至少在某些情况下,您不会停止循环,对吗? 这样您便可以看到第二步的重复步骤,依此类推...

忽略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');
    }
}

使用Array.some原型函数查找元素

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');
}

当脚本中断时,您将退出循环

因此,如果您寻找第二个客户,则将输入“ else”。 而且您已经从循环中退出,因此您将永远无法获得console.log

我会像这样更改代码(按注释中的建议进行编辑)

 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'); 

删除中断即可; 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');
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM