Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2021-12-20 16:36:27
forward
4827 people have browsed it

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
    Copy after login

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
    Copy after login

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
    Copy after login

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
    Copy after login

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
    Copy after login
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!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template