如果您不需要类型强制(因为使用了indexOf),您可以尝试以下操作:
var arr = [1, 2, 3];
var check = [3, 4];
var found = false;
for (var i = 0; i < check.length; i++) {
if (arr.indexOf(check[i]) > -1) {
found = true;
break;
}
}
console.log(found);
其中arr 包含目标项。最后,found 将显示第二个数组是否有至少一个与目标匹配。
当然,您可以将数字换成您想使用的任何东西 - 字符串很好,就像您的示例一样。
在我的具体示例中,结果应该是true,因为第二个数组的3 存在于目标中。
更新:
这是我将它组织成一个函数的方式(与之前相比有一些细微的变化):
var anyMatchInArray = (function () {
"use strict";
var targetArray, func;
targetArray = ["apple", "banana", "orange"];
func = function (checkerArray) {
var found = false;
for (var i = 0, j = checkerArray.length; !found && i < j; i++) {
if (targetArray.indexOf(checkerArray[i]) > -1) {
found = true;
}
}
return found;
};
return func;
}());
演示: http://jsfiddle.net/u8Bzt/
在这种情况下,可以修改函数以将 targetArray 作为参数传入,而不是在闭包中硬编码。
更新 2:
虽然我上面的解决方案可能有效并且(希望更)可读,但我相信处理我所描述的概念的“更好”方法是做一些不同的事情。上述解决方案的“问题”是循环内的indexOf 导致目标数组对于另一个数组中的每个项目都被完全循环。这可以通过使用“查找”(映射...JavaScript 对象文字)轻松“修复”。这允许在每个数组上进行两个简单的循环。这是一个例子:
var anyMatchInArray = function (target, toMatch) {
"use strict";
var found, targetMap, i, j, cur;
found = false;
targetMap = {};
// Put all values in the `target` array into a map, where
// the keys are the values from the array
for (i = 0, j = target.length; i < j; i++) {
cur = target[i];
targetMap[cur] = true;
}
// Loop over all items in the `toMatch` array and see if any of
// their values are in the map from before
for (i = 0, j = toMatch.length; !found && (i < j); i++) {
cur = toMatch[i];
found = !!targetMap[cur];
// If found, `targetMap[cur]` will return true, otherwise it
// will return `undefined`...that's what the `!!` is for
}
return found;
};
演示: http://jsfiddle.net/5Lv9v/
此解决方案的缺点是只能(正确)使用数字和字符串(和布尔值),因为这些值(隐式)转换为字符串并设置为查找映射的键。对于非文字值,这并不是很好/可能/容易做到的。