比较jquery中的两个数组

use*_*186 3 javascript jquery

使用此代码...

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); 
Run Code Online (Sandbox Code Playgroud)

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

现在我需要找到:

  • 如果数组“a”的元素在数组“b”中
  • 它在数组“b”中的索引是什么

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

Mat*_*orf 6

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

使用jQuery:

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

没有jQuery:

a.forEach( function( value ) {
    if( b.indexOf( value ) != -1 ) {
       console.log( b.indexOf( value ) );
    }
});
Run Code Online (Sandbox Code Playgroud)


Pri*_*sad 6

将两个数组都转换为字符串并进行比较

if (JSON.stringify(a) == JSON.stringify(b))
{
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

  • 当数组元素的顺序改变时,它将不起作用。 (2认同)