2011-06-07 77 views
1

我想測試一個數組內的值,並根據該結果相應地採取行動,即如果該項目不存在於正在測試的數組中,則將其添加到數組中。我已經在這方面花了太多時間,我真的可以用一些幫助。檢查陣列項目對另一個陣列

function FilterItems(attrName, attrValue, priceMin, priceMax) { 
     // check if item exists in filtered items 
     for (var i = 0; i < adlet.item.length; i++) { 
      if (adlet.item[i][attrName] == attrValue) { 
       var currentItem = adlet.item[i]; 
       if (filteredItems.length > 0) { 
        // console.log(filteredItems.length); 
        for (var x = 0; x < filteredItems.length; x++) {      
         if (filteredItems[x].OMSID == currentItem.OMSID) { 
          // match found 
          break;   
         } else { 
          // match not found, add to filtered items. 
          filteredItems.push(currentItem); 
         } 
        }   
       } else { 
        filteredItems.push(adlet.item[i]); 
        // console.log(filteredItems.length); 
       } 
      } 
     } 
+0

什麼是「filteredItems」以及它是如何定義的? adlet是什麼?它是如何定義的? – 2011-06-07 23:38:51

回答

1

您在每次找不到它的迭代中添加currentItemfilteredItems.push(currentItem);必須在循環之後,如果沒有找到被稱爲:

... 

    var found = false; // new 'found' var = true if currentItem is found 
    for (var x = 0; x < filteredItems.length; x++) { 
     if (filteredItems[x].OMSID == currentItem.OMSID) { 
      // match found 
      found = true; 
      break; 
     } 
    } 

    // match not found, add to filtered items. 
    if (!found) { 
     filteredItems.push(currentItem); 
    } 

} else { 
    filteredItems.push(adlet.item[i]); 
    // console.log(filteredItems.length); 
} 

... 
+0

有趣的是,我只是寫了相同的代碼...即使使用相同的變量名稱。 :) – Guffa 2011-06-07 23:39:59

1

/* 數組方法「的indexOf」實在太有用了忽略,如果你做任何事情的陣列。這裏有一個基於Mozilla代碼的墊片。

此處顯示的方法'add'與push相同,但只添加一個項目,如果它不在數組中。您可以使用多個參數添加多個項目。

「合併」將調用數組添加所有「新」項目被作爲參數數組, */

if(!Array.prototype.indexOf){ 
    Array.prototype.indexOf= function(what, i){ 
     i= i || 0; 
     var L= this.length; 
     while(i< L){ 
      if(this[i]=== what) return i; 
      ++i; 
     } 
     return -1; 
    } 
} 
Array.prototype.add= function(){ 
    var what, a= arguments, i= 0, L= a.length; 
    while(i<L){ 
     what= a[i++]; 
     if(this.indexOf(what)=== -1) this.push(what); 
    } 
    return this; 
} 
Array.prototype.merge= function(target){ 
    return this.add.apply(target, this); 
} 

var a1= [1, 2, 3, 4, 5, 6], a2= [2, 4, 6, 8, 10]; 
a1.merge(a2) 
/* returned value: (Array) 
2, 4, 6, 8, 10, 1, 3, 5 
*/ 
0

這是你的功能的簡化版本,只增加了過濾項內循環結束後:

function FilterItems(attrName, attrValue, priceMin, priceMax) { 
    for (var i = 0; i < adlet.item.length; i++) { 
     if (adlet.item[i][attrName] == attrValue) { 
     var currentItem = adlet.item[i]; 
     var found = false; 
     for (var x = 0; x < filteredItems.length; x++) { 
      if (filteredItems[x].OMSID == currentItem.OMSID) { 
       found = true; 
       break; 
      } 
     } 
     if (!found) 
      filteredItems.push(currentItem); 
     } 
    } 
}