设定
目标数组target
target = ['apple', 'orange', 'banana']
判断
其他数组中是否包含目标数组target
中的任意元素。
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
方法
- indexOf。返回true/false
let target = [1, 2, 3]
let check = [3, 4]
let found = false
for (let i = 0; i < check.length; i++) {
if (target.indexOf(check[i]) > -1) {
found = true
break
}
}
console.log(found); // true
found
表示check数组中是否包含至少一个元素在目标数组target
中.
- 导入
underscore
包,使用intersection
交叉方法。返回匹配项
返回为:目标数组
target
和其它数组的匹配项组成的数组,若无匹配项,则返回[]
。
let _ = require('underscore')
let target = [ 'apple', 'orange', 'banana']
let fruit2 = [ 'apple', 'orange', 'mango']
let fruit3 = [ 'mango', 'lemon', 'pineapple']
let fruit4 = [ 'orange', 'lemon', 'grapes']
console.log(_.intersection(target, fruit2)) // returns [apple, orange]
console.log(_.intersection(target, fruit3)) // returns []
console.log(_.intersection(target, fruit4)) // returns [orange]
- 遍历数组。 返回true/false
function Check(A) {
let target = ["apple", "banana", "orange"]
let i, j
let totalmatches = 0
for (i = 0; i < target.length; i++) {
for (j = 0; j < A.length; ++j) {
if (target[i] == A[j]) {
totalmatches++
}
}
}
if (totalmatches > 0) {
return true
} else {
return false
}
}
let fruits1 = new Array("apple", "grape")
console.log(Check(fruits1)) // true
let fruits2 = new Array("apple", "banana", "pineapple");
console.log(Check(fruits2)) // true
let fruits3 = new Array("grape", "pineapple");
console.log(Check(fruits3)) // false
- 导入
underscore
包,使用every
方法和include
方法结合。返回true/false
let a1 = [1,2,3]
let a2 = [1,2]
_.every(a1, function(e){ return _.include(a2, e) } ) //=> false
_.every(a2, function(e){ return _.include(a1, e) } ) //=> true
网友评论