简体   繁体   English

比较两个JavaScript数组?

[英]comparing two javascript arrays?

I want to compare two arrays with each other and see if there is a match, and if there is do something. 我想将两个数组相互比较,看看是否有匹配项,是否有做某事。

var answers = new Array("a","b","c","d", "e");
var correct = new Array("a","d");
// do a for loop
// if there's a match console.log(letter + "is the correct answer")

Try using this: 尝试使用此:

for(var i = 0; i < answers.length; i++) {
    for(var j = 0; j < correct.length; j++){
        if (answers[i] === correct[j]){ 
            console.log(answers[i]+ " is the correct answer")
            break;
        }
    }
}

Try this code: 试试这个代码:

var a = [1,2,3,4]
  , b = [1,3,5,7,9]
  , c = ['a','b','c'];

function findDups( arr1, arr2 ) {
  var arrs = [ arr1, arr2 ].sort(function( a,b ) {
    return a.length > b.length;
  });
  return arrs[0].filter(function( v ) {
    return ~arrs[1].indexOf( v ); 
  });
}

function hasDups( arr1, arr2 ) {
  return !!findDups( arr1, arr2 ).length;
}

console.log( findDups( a,b ) ); //=> [1, 3]
console.log( hasDups( a,c ) ); //=> false

Look this post, there is a code to compare disorder arrays: http://blog.maxcnunes.net/2012/08/10/comparacao-de-arrays-desordenados-javascript/ 看一下这篇文章,有一个代码可以比较无序数组: http : //blog.maxcnunes.net/2012/08/10/comparacao-de-arrays-desordenados-javascript/

ps: the post is in portuguese, but you can use any translater to understand ps:帖子是葡萄牙语,但您可以使用任何翻译程序来理解

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM