簡體   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