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 arrayfor (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 beforefor (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;};
/*** @description determine if an array contains one or more items from another array.* @param {array} haystack the array to search.* @param {array} arr the array providing items to check for in the haystack.* @return {boolean} true|false if haystack contains at least one item from arr.*/var findOne = function (haystack, arr) {return arr.some(function (v) {return haystack.indexOf(v) >= 0;});};
正如@loganfsmyth所指出的,您可以在ES2016中将其缩短为
/*** @description determine if an array contains one or more items from another array.* @param {array} haystack the array to search.* @param {array} arr the array providing items to check for in the haystack.* @return {boolean} true|false if haystack contains at least one item from arr.*/const findOne = (haystack, arr) => {return arr.some(v => haystack.includes(v));};
const contains = (arr1, mainObj) => arr1.some(el => el in mainObj);const includes = (arr1, mainObj) => arr1.every(el => el in mainObj);
用法:
const mainList = ["apple", "banana", "orange"];// We make object from array, you can use your solution to make itconst main = Object.fromEntries(mainList.map(key => [key, true]));
contains(["apple","grape"], main) // => truecontains(["apple","banana","pineapple"], main) // => truecontains(["grape", "pineapple"], main) // => false
includes(["apple", "grape"], main) // => falseincludes(["banana", "apple"], main) // => true