如何檢查第一個數組中是否存在至少一個數值? 例如,如何檢查car_1數組和car_2數組上是否有寶馬?檢查數組值是否存在於其他陣列
var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
如何檢查第一個數組中是否存在至少一個數值? 例如,如何檢查car_1數組和car_2數組上是否有寶馬?檢查數組值是否存在於其他陣列
var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
完整的解決方案:
// will return true if at least one element of cars_1 is in cars_2
cars_1.some(function (e) {
return cars_2.indexOf(e) >= 0;
});
它適用於所有主流瀏覽器嗎? – 2013-03-23 01:02:40
查看[鏈接]的底部(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/some#Browser_compatibility) – tjameson 2013-03-23 01:03:02
一個快速簡便的方法:
function overlap(arr1,arr2) {
for(var i = 0; i < arr1.length; ++i)
if(arr2.indexOf(arr1[i]) != -1)
return true;
return false;
}
一個快速簡單的答案:
for (var i =0; i<cars_1.length; i++){
for (var j=0; j<cars_2.length; j++){
if(cars_2[j] == cars_1[i]) return true;
}
}
return false;
編輯: OK,響應評論:) EDIT2更高效: OK,甚至更有效的:)
一個簡單的O( m + n)解決方案:
var cars_1 = ["Saab","Volvo","BMW"];
var cars_2 = ["Honda","Mazda","BMW", "suzuki"];
// build up a hash table of the cars in the 1st sequence:
var set_1 = {};
for (var i = 0; i < cars_1.length; ++i) {
set_1[cars_1[i]] = true;
}
// look if there is a car in sequence 2 that is in set_1:
var has_intersection = false;
for (var i = 0; i < cars_2.length; ++i) {
if (set_1[cars_2[i]] === true) {
has_intersection = true;
break;
}
}
也適用於任何瀏覽器。
如果您的瀏覽器支持它,您可以使用.some
方法。
var cars1 = [...],
cars2 = [...];
var res = cars1.some(function(a) {
return cars2.indexOf(a) > -1;
});
如果沒有,那麼你可以創建自己的墊片:
function some(list, callback) {
var len = list.length;
for (var i = len; i--;) {
if (callback(list[i], i)) {
return true;
}
}
return false;
}
var res = some(cars1, function(a) {
return cars2.indexOf(a) > -1;
});
如果您的瀏覽器不支持不支持它,你應該只包括鏈接頁面的代碼... – Esailija 2013-03-23 01:07:09
您還可以使用「過濾器」的方法:
var cars_1 = new Array("Saab","Volvo","BMW");
var cars_2 = new Array("Honda","Mazda","BMW", "suzuki");
var cars_3 = new Array("Audi");
/* with underscore.js */
var _hasIntersection = function (arr1, arr2) {
var intArr = _.filter(arr1, function (elem) { return arr2.indexOf(elem) > -1 });
return intArr.length;
}
/* or using Array.prototype.filter */
var hasIntersection = function (arr1, arr2) {
var intArr = arr1.filter(function (elem) { return arr2.indexOf(elem) > -1 });
return intArr.length;
}
console.log(_hasIntersection(cars_1, cars_2)); // 1
console.log(hasIntersection(cars_1, cars_2)); // 1
console.log(hasIntersection(cars_1, cars_3)); // 0
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
很可能有至少三種方法來做到這一點,不包括像JQuery – Ryan 2013-03-23 00:57:41
任何方向的庫? – 2013-03-23 00:58:17
爲什麼沒有把信息放在那裏有更多答案? – kay 2013-03-23 01:05:07