如何比较数组中的值以查找另一个数组中的一个或多个匹配项?

时间:2021-02-28 20:34:52

I try compare two arrays to find one or more than one matches of them. Somebody help me please?

我尝试比较两个数组,找到它们中的一个或多个匹配。有人帮帮我吗?

http://jsfiddle.net/gmRDk/2/

$("button").click(function(i) {

var products = [2, 5, 6, 7, 200];
var item_id = [2, 1, 6, 200];

$.each(item_id, function() {
if ($.inArray(this, products) !== -1) {
    alert('Match Prod: ' + this);
} else {
    alert('Not Match: ' + this);
}
});
}); 

2 个解决方案

#1


2  

In the each callback this points to a object, not to the value

在每个回调中,这指向一个对象,而不是值

var products = [2, 5, 6, 7, 200];
var item_id = [2, 1, 6, 200];
$.each(item_id, function(idx, value) {
    if ($.inArray(value, products) !== -1) {
        console.log('Match Prod: ' + value);
    } else {
        console.log('Not Match: ' + value);
    }
});

Demo: Fiddle

#2


0  

  $("button").click(function(i) {

  var products = [2, 5, 6, 7, 200];
var item_id = [2, 1, 6, 200];
    var len=products.length;
    for(i=0;i<len;i++){
  if($.inArray(products[i],item_id)==-1)
  {
      alert("not in array item_Id   :"+products[i]);
  }
        else{
            alert("in array item_ID  :"+products[i]);
        }
    }
});

you can check each individual element in the array like this . demo :http://jsfiddle.net/gmRDk/3/

您可以像这样检查数组中的每个元素。演示:http://jsfiddle.net/gmRDk/3/

#1


2  

In the each callback this points to a object, not to the value

在每个回调中,这指向一个对象,而不是值

var products = [2, 5, 6, 7, 200];
var item_id = [2, 1, 6, 200];
$.each(item_id, function(idx, value) {
    if ($.inArray(value, products) !== -1) {
        console.log('Match Prod: ' + value);
    } else {
        console.log('Not Match: ' + value);
    }
});

Demo: Fiddle

#2


0  

  $("button").click(function(i) {

  var products = [2, 5, 6, 7, 200];
var item_id = [2, 1, 6, 200];
    var len=products.length;
    for(i=0;i<len;i++){
  if($.inArray(products[i],item_id)==-1)
  {
      alert("not in array item_Id   :"+products[i]);
  }
        else{
            alert("in array item_ID  :"+products[i]);
        }
    }
});

you can check each individual element in the array like this . demo :http://jsfiddle.net/gmRDk/3/

您可以像这样检查数组中的每个元素。演示:http://jsfiddle.net/gmRDk/3/