0

我尝试比较两个数组以找到其中一个或多个匹配项。有人帮我吗?

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

2 回答 2

3

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

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

演示:小提琴

于 2013-07-26T03:18:09.353 回答
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]);
        }
    }
});

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

于 2013-07-26T05:38:38.393 回答