Home > Article > Web Front-end > How to determine whether an array contains a certain child element in es6
Method: 1. Use the indexOf() function, the syntax is "array object.indexOf(value)", if the element position is returned, it is included, if "-1" is returned, it is not included; 2. Use includes() Function, syntax "array object.includes(value)", returns true if it is included, otherwise it is not included.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Determine whether the array contains a certain child element
Method 1: Use the indexOf() function
indexOf is used to find the position of an element, and returns -1 if it does not exist.
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log(arr.indexOf('c')) console.log(arr.indexOf('z'))
Note: The indexOf() function has two small shortcomings when judging whether the array contains an element
First The first is that it will return -1 and the position of the element to indicate whether it is included. There is no problem in terms of positioning, but it is not semantic enough.
Another problem is that it cannot determine whether there are NaN elements.
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log(arr.indexOf(NaN))
Method 2: Use the includes() function
includes() function can Used to detect whether an array contains a certain value
includes() function solves the above two problems of indexOf except that it cannot be positioned. It directly returns true or false to indicate whether it contains an element, and it is also effective for NaN.
const arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log(arr.includes('c')) console.log(arr.includes('z')) console.log(arr.includes(NaN))
[Related recommendations: javascript video tutorial, web front-end】
The above is the detailed content of How to determine whether an array contains a certain child element in es6. For more information, please follow other related articles on the PHP Chinese website!