-1

我想比较两个数组,看看是否匹配,是否有做某事。

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")
4

3 回答 3

3

尝试使用这个:

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;
        }
    }
}
于 2013-01-10T10:00:55.133 回答
0

看这个帖子,有比较无序数组的代码:http: //blog.maxcnunes.net/2012/08/10/comparacao-de-arrays-desordenados-javascript/

ps:帖子是葡萄牙语的,但你可以使用任何翻译器来理解

于 2013-01-10T12:01:24.817 回答
0

试试这个代码:

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
于 2013-01-10T10:10:20.337 回答