Preface
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
Let’s 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 respectively and the position where n 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 sees nothing interesting here, don’t worry, here is 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 the number to the string '2' and then execute.
Use of Number type
You may wonder if the number type has an indexOf method because it will perform implicit conversion! Let me tell you clearly that no, in the above example
let num = 2016; num.indexOf(2); //Uncaught TypeError: num.indexOf is not a function
, 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 are possible. People who are obsessed with code prefer the third type ✅
Array type use
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 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 example is 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 subscript is matched and returned.
arr.indexOf(‘o’) outputs -1 because this method does not perform indexOf matching again on a per-element basis.
arr.indexOf(‘2016’) outputs 1 because this method returns the table below of the first array element from the beginning until the match is reached, rather than returning all matching subscripts.
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).
It is clear at a glance, what is 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 a message to communicate.
For more articles related to simply talking about the indexOf method in JS arrays, please pay attention to the PHP Chinese website!

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

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.

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.

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.

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 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

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.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
