In es6, you can use the includes() method of the array to determine whether the array contains a certain value. This method can be used to detect whether the array contains a certain value. The syntax is "array object.includes(value)".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
In ES5, Array already provides indexOf to find the position of an element. If it does not exist, it returns -1. However, this function has two minor shortcomings when determining whether the array contains an element. The first is that it returns -1 and the position of the element are used 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.
For example:
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log('%s', arr1.indexOf(NaN))
result:
-1
ES6 provides the Array.includes() function to determine whether a certain element is included. In addition to being unable to locate it, it solves the above two problems of indexOf. . It directly returns true or false to indicate whether it contains an element, and it is also effective for NaN.
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log('%s', arr1.includes('c')) console.log('%s', arr1.includes('z')) console.log('%s', arr1.includes(NaN))
result:
true false
The second parameter of the
trueincludes() function indicates the starting position of the judgment.
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', NaN] console.log('%s', arr1.includes('d', 1)) console.log('%s', arr1.includes('d', 3)) console.log('%s', arr1.includes('d', 4))
result:
true true falseThe
second parameter can also be a negative number, indicating the number from the right, but does not change the direction of the search, the search direction is still from left to right.
console.log('%s', arr1.includes('k', -1)) console.log('%s', arr1.includes('k', -2)) console.log('%s', arr1.includes('i', -3))
result:
false true false
summary:
includes() method, used to detect whether an array contains a certain value, can judge NaN, and directly returns true/false, which is more intuitive;
indexOf() method, used to find the position of an element, cannot judge NaN , returns -1, which means it is not included, and non-1 means the current included position.
Both methods have their own advantages and disadvantages, which depend on the actual situation. If the element contains NaN, use includes(), otherwise either can be used.