本文介绍了检查一个数组是否包含 JavaScript 中另一个数组的任何元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个目标数组["apple","banana","orange"]
,我想检查其他数组是否包含任何一个目标数组元素.
I have a target array ["apple","banana","orange"]
, and I want to check if other arrays contain any one of the target array elements.
例如:
["apple","grape"] //returns true;
["apple","banana","pineapple"] //returns true;
["grape", "pineapple"] //returns false;
我如何在 JavaScript 中做到这一点?
How can I do it in JavaScript?
推荐答案
Vanilla JS
ES2016:
const found = arr1.some(r=> arr2.includes(r))
ES6:
const found = arr1.some(r=> arr2.indexOf(r) >= 0)
工作原理
some(..)
根据测试函数检查数组的每个元素,如果数组的任何元素通过测试函数,则返回真,否则返回假.indexOf(..) >=0
和 includes(..) 都返回 true.
some(..)
checks each element of the array against a test function and returns true if any element of the array passes the test function, otherwise, it returns false. indexOf(..) >= 0
and includes(..)
both return true if the given argument is present in the array.
这篇关于检查一个数组是否包含 JavaScript 中另一个数组的任何元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!