javascript查找值是否为非IN数组

时间:2022-11-15 21:28:54

My problem with this is that the loop keeps going into the if statement even for duplicate barcodes. I'm trying to enter the if statement only for unique barcodes but at the end of the loop myArray has duplicates in it....why?

我的问题是即使对于重复的条形码,循环也会继续进入if语句。我正在尝试仅为唯一条形码输入if语句,但在循环结束时myArray中有重复项....为什么?

var myArray = new Array();  var i = 0;
$("li.foo").each(function(){
   var iBarCode = $(this).attr('barcode');
   if( !( iBarCode in myArray ) ){
      myArray[i++] = iBarCode;
      //do something else
   }
});

2 个解决方案

#1


35  

Jquery has an inArray() function.

Jquery有一个inArray()函数。

var myArray = new Array();  var i = 0;
$("li.foo").each(function(){
   var iBarCode = $(this).attr('barcode');
   if( $.inArray(iBarCode, myArray) == -1 ){
      myArray[i++] = iBarCode;
      //do something else
   }
});

#2


9  

The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.

in关键字搜索属性,例如,当您想知道对象是否有某些方法可用时。由于您正在查找值,因此它始终返回false。

You should instead use an array search function as Gazler advises.

你应该使用Gazler建议的数组搜索功能。

#1


35  

Jquery has an inArray() function.

Jquery有一个inArray()函数。

var myArray = new Array();  var i = 0;
$("li.foo").each(function(){
   var iBarCode = $(this).attr('barcode');
   if( $.inArray(iBarCode, myArray) == -1 ){
      myArray[i++] = iBarCode;
      //do something else
   }
});

#2


9  

The in keyword search for properties, for instance when you want to know if an object has some method available. Since you are looking for values, it always returns false.

in关键字搜索属性,例如,当您想知道对象是否有某些方法可用时。由于您正在查找值,因此它始终返回false。

You should instead use an array search function as Gazler advises.

你应该使用Gazler建议的数组搜索功能。