search
HomeWeb Front-endJS TutorialAnalysis of indexOf method in JS array (with examples)

The content of this article is about the analysis of the indexOf method in JS arrays (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the past two days, I have been helping a friend work on a project at home. The indexOf method of the array was used in the project, and I found an article that felt very good. I organized it by the way to prevent the link from being lost.

I believe everyone is familiar with indexOf. It is particularly commonly used when judging whether a string contains substrings. It is a useful tool for students who are not familiar with regular expressions. This article uses an example to talk about the indexOf method based on a problem I encountered recently. This article is an accumulation of small knowledge points and is not a topic for in-depth discussion. Therefore, the second parameter of indexOf() is not explained here. I believe everyone knows the role of the second parameter.

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 respectively The position at which it occurs in the string. 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 rush and let’s give another example

let numStr = '2016';
 
numStr.indexOf('2'); //0
numStr.indexOf(2); //0

There is a small point here that indexOf will do simple type conversion, convert numbers into strings '2' and then execute .

Use of Number type

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

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

must 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, actually both are fine. People who are obsessed with code prefer the third one √ .

Usage of array type

Everyone cheer up, the big boss is coming.
Everyone is familiar with array methods, but they ignore that arrays have the indexOf method (my personal feeling).
Talking nonsense without practicing, what problems did you encounter, and what are the key points to 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') Output 0 because 'orange' is the 0th element of the array, the index is matched and returned.
arr.indexOf('o') Output -1 because this method does not perform indexOf matching 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 until the match is reached, rather than returning all matching indexes.
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,used here Is strictly equal to (===) . 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 above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, You can leave messages to communicate.

  • String: indexOf will perform type conversion on the number 0 and convert it to the string '0'.

  • Number: There is no indexOf method. Need to convert numeric type to string. There are three methods. Direct string, string toString, string concatenation.

  • Array: Arrays also have the indexOf method, but when doing type judgment, strict equality is used, that is, ===.

The above is the detailed content of Analysis of indexOf method in JS array (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:https://segmentfault.com/a/1190000017001710. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

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

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version