search
HomeWeb Front-endJS TutorialDetailed explanation of indexOf method in JavaScript array

I recently encountered a small problem with the code and I will simplify it into a small example to show you.

You will be rewarded if you pay attention in the end. Children's shoes with a solid foundation can jump directly to array type and use.

Speaking of indexOf, everyone is familiar with it. It is especially commonly used when judging whether a string contains a substring (a useful tool for students who are not familiar with regular expressions).

Usage of String type

Review the well-known string usage, for example

let str = 'orange';

str.indexOf('o');  //0
str.indexOf('n');  //3
str.indexOf('c');  //-1

Here 0 and 3 are o and n appearing in the string respectively Location. The starting index is 0. And -1 means no match.

Someone once asked me why -1 is not null or undefined. Ask the person who made the rules! A look of helplessness.

Everyone feels that there is no highlight here, don’t worry, let’s give another example

let numStr = '2016';

numStr.indexOf('2');  //0
numStr.indexOf(2);  //0

There is a small point here that indexOf can do simple type conversion. Convert the number into a string '2' and then execute it.

Use of Number type

You may wonder whether the number type has an indexOf method because it will do implicit conversion! Let me tell you clearly that no, in the example

let num = 2016;

num.indexOf(2);  //Uncaught TypeError: num.indexOf is not a function

above, do you have to use the indexOf method on the number type? Then convert it into a string, and then write

//二逼青年的写法
num = '2016';
num.indexOf(2);  //0

//普通青年的写法
num.toString().indexOf(2);  //0

//文艺青年的写法
('' + num).indexOf(2);  //0

in the above example. The first way of writing is simple and direct, and it is not impossible for known shorter numbers. But what should we do when the num variable changes for different data?

The second way of writing is the most commonly used, but it is a little longer than the third way of writing. Haha, in fact, all is OK. People who are obsessed with code like the use of the third

Array type

Everyone, cheer up, the big boss is coming.

Everyone is familiar with the array method, but they have overlooked that the array has the indexOf method (my personal feeling).

Talking nonsense without practicing, what problems have you encountered, and what should you pay attention to?

let arr = ['orange', '2016', '2016'];

arr.indexOf('orange');  //0
arr.indexOf('o');  //-1

arr.indexOf('2016');  //1
arr.indexOf(2016);  //-1

The examples are not broken down in detail here. Four use cases are enough to illustrate the problem.

  • arr.indexOf(‘orange’) outputs 0 because ‘orange’ is the 0th element of the array, and the index is matched and returned.

  • arr.indexOf(‘o’) outputs -1 because this method does not perform an indexOf match again on a per-element basis.

  • arr.indexOf(’2016′) Output 1 Because this method returns the following list of the first array element from the beginning of the match until the match is reached, rather than returning the index of all matches.

  • arr.indexOf(2016) Output -1 Note: No implicit type conversion will be done here.

Now that the pit has been discovered, we might as well get to the bottom of it. Go to the MDN official website to find out. Friends who are interested in this topic can jump directly to Array.prototype.indexOf()

For those who just want to know more, here is the official Description.

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

Clear at a glance, Strict equals (===) are used here. Please pay more attention when making similar judgments. Don't make the mistake of thinking that numbers will be converted to strings, and strings will not be converted to numbers.

Summary

The accumulation of small knowledge points is not a topic for in-depth discussion, so the second parameter of indexOf() is not explained here. I believe everyone knows the role of the second parameter. If you know, you can look at String.prototype.indexOf() here, and then take a look at the second parameter in conjunction with the link to the array above.

The above is the detailed explanation of the indexOf method in JavaScript arrays. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Statement
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.