Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

javascript - 检查一个数组是否包含JavaScript中另一个数组的任何元素(Check if an array contains any element of another array in JavaScript)

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","banana","orange"] ,我想检查其他数组是否包含任何目标数组元素。)

For example:

(例如:)

["apple","grape"] //returns true;

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

["grape", "pineapple"] //returns false;

How can I do it in JavaScript?

(如何在JavaScript中完成?)

  ask by Alex translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Vanilla JS

(香草JS)

ES2016:

(ES2016:)

const found = arr1.some(r=> arr2.includes(r))

ES6:

(ES6:)

const found = arr1.some(r=> arr2.indexOf(r) >= 0)

How it works

(这个怎么运作)

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.

(some(..)根据测试函数检查数组的每个元素,如果数组的任何元素通过测试函数,则返回true,否则返回false。)

indexOf(..) >= 0 and includes(..) both return true if the given argument is present in the array.

(如果给定参数存在于数组中,则indexOf(..) >= 0includes(..)都返回true。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...