2011-06-07 81 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); 
     } 
    } 
}