search
HomeWeb Front-endJS TutorialHow to operate arrays and strings in js

How to operate arrays and strings in js

Mar 31, 2018 pm 05:13 PM
javascriptstringmethod

This article mainly shares with you the operation methods of arrays and strings in js, mainly in the form of text and code. I hope it can help everyone.

1. Array operation method

// 1.数组的操作方法
var a = [];
a.unshift()		/*在数组的开头添加一个或者多个元素,返回新长度;IE9+*/
a.shift()		/*删除数组中的第一个元素,返回删除的元素*/
a.push()		/*往数组的末尾添加一个或多个元素,返回新长度*/
a.pop()			/*删除并返回数组的最后一个元素*/

a.slice('start', 'end')	/*不修改原数组,返回一个新数组*/
a.concat()		/*不修改原数组,返回一个新数组。不传参数时,复制数组;传参数时连接数组,可以有多个数组参数;*/
a.splice()		/*删除数组:两个参数,第一个是开始的位置,第二个是删除的长度
				插入元素:至少3个参数,第一个是开始的位置,第二个是0,后面是要插入的元素(可以有多个)
				替换元素:至少3个参数,第一个是开的位置,第二个是替换的个数,后面是要替换的元素*/
a.reverse()		/*反转数组*/
a.sort()		/*用特定的方法对数组进行排列,接收一个排序函数,该函数接收两个参数,
				如果第一个参数在前面,返回一个负数;如果第二个参数在前面,返回一个正数;如果两个参数相等,返回0*/
a.indexOf()		/*在数组中查找元素,两个参数,第一个参数时要查找的元素;第二个参数是要开始查找的位置(该参数可以没有)*/
a.lastIndexOf()		/*从数组的后面开始查找元素,与indexOf相同,只是查找方向不同*/
a.join()		/*把数组格式化成字符串,接收一个参数,即:分隔符。如果不传参数或传入undefined,则以逗号分隔*/
a.toString()		/*返回以逗号为分隔符的数组中的元素组成的字符串*/

a instanceof Array	/*检测是否为数组,如果是,返回true*/
Array.isArray(a)	/*检测是否为数组,如果是,返回true。IE9+*/

2. String operation method

// 字符串操作方法
var b = '54545';
b.concat()			/*拼接字符串,返回新的字符串,不改变原字符串。实践中最常用的是+操作符*/
b.charAt()			/*接收一个参数(字符串中的位置),返回字符串中某位置上的字符*/
b.charCodeAt()			/*与charAt用法相同,返回的是该字符的字符编码*/
String.fromCharCode()	        /*传入字符串的编码,把编码解析为字符串并返回该字符串。可接收多个编码参数*/
b.slice('start', 'end')		/*返回一个新的字符串,不不包含end,不改变原字符串*/
b.substring('start', 'end')	/*与slice一样*/
b.substr('start', 'length')	/*返回一个新字符串,不改变原字符串*/
b.indexOf()			/*在字符串中从前往后查找字符,没找到就返回-1。接收两个参数:第一个参数时要查找的字符;第二个参数是(可选的)开始查找的位置*/
b.lastIndexOf()			/*与indexOf用法相同,改方法是从后往前查找*/
b.search()			/*在字符串中查找,并返回位置。接收一个参数(要查找的字符串),如果没找到,返回-1.从左向右查找*/
b.trim()			/*创建一个字符串副本,删除前置及后缀的所有空格,返回结果。 IE9+*/
b.toLocaleLowerCase()	        /*字符串大写转为小写(针对地区特定的方法,推荐使用)*/
b.toLocaleUpperCase()	        /*字符串小写转为大写(针对地区特定的方法,推荐使用)*/
b.toLowerCase()			/*字符串大写转为小写*/
b.toUpperCase()			/*字符串小写转为大写*/
b.localeCompare('str')	        /*比较字符串b与str,并返回0或一个正数或一个负数。如果在字母表中b在str的前面,就返回一个负数;在后面,返回一个正数;相等返回0*/
b.replace()			/*查找并替换(不改变原字符串),返回一个新字符串,接收两个参数。第一个参数:要替换(查找)的字符串;第二个:要替换成的字符串。*/
// 例子:
function replac() {
	var text = "cat,bat,sat,fat";
	var result1 = text.replace('at', 'ond');				/*第一个参数是字符串*/
	console.log(result1);	    /*"cond,bat,sat,fat"*/			/*只替换第一个*/
	var result2 = text.replace(/at/g, 'ond');				/*第一个参数是正则表达式*/
	console.log(result2);	    /*"cond,bond,sond,fond"*/		        /*全部替换*/
	console.log(text);
};
replac();

Related recommendations:

JS interception and splitting characters Common methods for strings

JS string to remove duplicate characters

js implements string conversion to date format

The above is the detailed content of How to operate arrays and strings in js. For more information, please follow other related articles on the PHP Chinese website!

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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.