Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the differences between includes () and indexOf () in JS

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report