【问题标题】:How to compare values in array to find one or more matches in another array?如何比较数组中的值以在另一个数组中找到一个或多个匹配项?
【发布时间】:2013-07-26 03:14:46
【问题描述】:

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

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

【问题讨论】:

  • 您至少需要两个循环来查找匹配项,从一个中获取每个元素并与另一个进行比较。如果您尝试一下并发布您遇到的错误类型会更好。

标签: jquery arrays each


【解决方案1】:

在每个回调中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);
    }
});

演示:Fiddle

【讨论】:

    【解决方案2】:
      $("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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 2016-02-14
      • 1970-01-01
      • 2021-05-16
      相关资源
      最近更新 更多