使用此代码...
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”中。
现在我需要找到:
- 如果数组“a”的元素位于数组“b”中
- 它在数组“b”中的索引是什么
例如“随机数据”在两个数组中,所以我需要返回它在数组 b 中的位置,即索引为零。
最佳答案
关于您的评论,这里有一个解决方案:
使用 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 ) );
}
});
关于javascript - jquery 比较两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17856846/