JavaScript

JavaScript----4种方法:检查一个数组中是否包含另一

2021-03-06  本文已影响0人  扮猪老虎吃

设定

目标数组target

target = ['apple', 'orange', 'banana']

判断

其他数组中是否包含目标数组target中的任意元素。

["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;

方法

  1. 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中.

  1. 导入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]
  1. 遍历数组。 返回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
  1. 导入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
上一篇下一篇

猜你喜欢

热点阅读