What are the differences between includes () and indexOf () in JS
This article is about the differences between includes () and indexOf () in JS. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. Basic differences
Both includes () and indexOf () are used to check whether the array contains certain elements, includes () returns a Boolean value, indexOf () returns an index value, if no-1 is returned.
Let arr = [1, 2, 3] arr.indexOf (0) / /-1arr.indexOf (2) / / 1arr.includes (2) / / true
2. Check NAN and undefined
Because indexOf () compares values strictly according to the = = operator, indexOf () cannot check NAN, but includes () can
Let arr = [NaN,] arr.indexOf (NaN) / /-1arr.indexOf (undefined) / /-1arr.includes (NaN) / / truearr.includes (undefined) / / true
3. Check-0 and + 0
Includes () and indexOf () do not distinguish between-0 and + 0. When judging, they think that they are the same.
Let arr = [+ 0] arr.includes (- 0) / truearr.indexOf (- 0) / / 0
4. Complex data types cannot be checked
The two can only judge simple data types, but not complex data types such as objects and arrays.
Let arr = [{av v 1}, {av v 2}] arr.includes ({av v 1}) / / falsearr.indexOf ({av v 1}) / /-1
5. IndexOf () can be used as a string
Returns the position where the specified character first appears, and there is an implicit conversion
Let str = 'a1b2c3'str.indexOf (' 2'); / / 3str.indexOf (1); / / 3 Thank you for reading! This is the end of the article on "what are the differences between includes () and indexOf () in JS". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!