Javascript javascript查找值是否不在数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6541536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:12:26  来源:igfitidea点击:

javascript find if value is NOT IN array

javascriptjqueryarrayseach

提问by sadmicrowave

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

回答by Gazler

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

回答by slaphappy

The inkeyword 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 的建议使用数组搜索功能。