在jquery中比较两个数组 [英] Comparing two arrays in jquery

查看:186
本文介绍了在jquery中比较两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码......

Using this code...

var a = ['volvo','random data'];
var b = ['random data'];
var unique = $.grep(a, function(element) {
    return $.inArray(element, b) == -1;
});

var result = unique ;

alert(result); 

...我能够找到数组a中哪个元素不在数组中b 。

...I am able to find which element of Array "a" is not in Array "b".

现在我需要找到:


  • 如果数组元素为a 在数组中b

  • 数组中的索引是什么b

例如,随机数据在两个数组中,所以我需要在数组b中返回它的位置,这是零索引。

For example "Random data" is in both arrays, so I need to return its position in Array b which is zero index.

推荐答案

关于你的评论,这是一个解决方案:

Regarding your comment, here is a solution:

with jQuery:

$.each( a, function( key, value ) {
    var index = $.inArray( value, b );
    if( index != -1 ) {
        console.log( index );
    }
});

没有 jQuery:

a.forEach( function( value ) {
    if( b.indexOf( value ) != -1 ) {
       console.log( b.indexOf( value ) );
    }
});

这篇关于在jquery中比较两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆