This article will briefly compare the includes() and indexOf() methods in JavaScript and talk about their differences. I hope it will be helpful to you!
1. Basic difference
-1. [Related recommendations:
javascript learning tutorial]
let arr = [1,2,3] arr.indexOf(0) // -1 arr.indexOf(2) // 1 arr.includes(2) // true
2. Check NAN and undefined
let arr = [NaN,] arr.indexOf(NaN) // -1 arr.indexOf(undefined) // -1 arr.includes(NaN) // true arr.includes(undefined) // true
3. Check -0 and 0
let arr = [+0] arr.includes(-0) // true arr.indexOf(-0) // 0
4. Complex data types cannot be checked
let arr = [{a:1},{a:2}] arr.includes({a:1}) // false arr.indexOf({a:1}) // -1
5. indexOf() can be used for strings
let str = 'a1b2c3' str.indexOf('2')); //3 str.indexOf(1)); //3
programming video! !
The above is the detailed content of includes() vs indexOf() in JS, let's talk about their differences. For more information, please follow other related articles on the PHP Chinese website!