Home  >  Article  >  Web Front-end  >  includes() vs indexOf() in JS, let's talk about their differences

includes() vs indexOf() in JS, let's talk about their differences

青灯夜游
青灯夜游forward
2021-12-20 16:36:274840browse

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!

includes() vs indexOf() in JS, let's talk about their differences

1. Basic difference

  • ##includes() and indexOf() They are all used to check whether the array contains certain elements. The return value of includes() is a Boolean value, and indexOf() returns the index value. If not, it returns

    -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

  • Because indexOf() strictly follows the === operator to compare values, indexOf() cannot check NAN, but includes() can

  • let arr = [NaN,]
    arr.indexOf(NaN)	// -1
    arr.indexOf(undefined) // -1
    arr.includes(NaN)	// true
    arr.includes(undefined)	// true

3. Check -0 and 0

  • includes() and indexOf() do not distinguish between -0 and 0. When judging, Thinking that the two are the same

  • let arr = [+0]
    arr.includes(-0) // true
    arr.indexOf(-0) // 0

4. Complex data types cannot be checked

  • Both can only judge simple data types, but cannot judge complex data types such as objects and arrays

  • let arr = [{a:1},{a:2}]
    arr.includes({a:1}) // false
    arr.indexOf({a:1}) // -1

5. indexOf() can be used for strings

  • Returns the position where the specified character appears for the first time, and there is an implicit conversion

  • let str = 'a1b2c3'
    str.indexOf('2')); //3
    str.indexOf(1)); //3
More Programming For related knowledge, please visit:

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete