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 the includes() function, the syntax is "array object .includes(value)", if true is returned, it is included, otherwise it is not included.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 determines whether the array contains a certain sub-element.
Method 1: Use the indexOf() function
indexOf to find the position of a certain element. If it does not exist, it returns -1.
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 determining whether an array contains an element.
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
The includes() function can be used to detect whether an array contains a certain value.
The 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))