下面是使用async.some
var async = require('async');
var arr0 = [0];
var arr1 = [1,2,3];
var arr2 = [2,3,4];
var arr3 = [1,5,3];
function testExist(arrayToCheck, arrayInCheck, mainCallback){
async.some(arrayToCheck, function(item, callback){
if(arrayInCheck.indexOf(item) != -1){
callback(true);
}
else{
callback(false);
}
}, function(result){
mainCallback(result);
});
}
testExist(arr0, arr1, function(result){
console.log(result);
});
testExist(arr1, arr2, function(result){
console.log(result);
});
testExist(arr2, arr3, function(result){
console.log(result);
});
下面是示例,而不使用異步庫的一種方式,Node.js的支持array.some
var arr0 = [0];
var arr1 = [1,2,3];
var arr2 = [2,3,4];
var arr3 = [1,5,3];
function testWithoutAsyncLibExist(arrayToCheck, arrayInCheck, callback){
var check = arrayToCheck.some(function(el, index, array){
return (arrayInCheck.indexOf(el) != -1);
});
callback(check);
}
testWithoutAsyncLibExist(arr0, arr1, function(result){
console.log(result);
});
testWithoutAsyncLibExist(arr1, arr2, function(result){
console.log(result);
});
testWithoutAsyncLibExist(arr2, arr3, function(result){
console.log(result);
});
是否可以將數組轉換成HashSets(地圖)並將它們相交?如果交集爲空 - 數組沒有公共項目,否則交集是常用項目。當交點爲O(n)時,組合循環爲O(n^2) –