Recently I am sorting out the basics of js, starting with arrays and strings.
string Commonly used methods:
1.substring (start starting position index, end ending position index) The intercepted position does not include the characters at the end position. Just write one parameter to indicate interception from the starting position. At the end
var str='abcdefg'; str.substring(1) //得到bcdefg str.substring(1,3) //得到bc
When entering a negative value, the negative value will be changed to 0, whichever is smaller will be used as the starting position
str.substing(-1,1) => str.substring(0,1) //a
str.substring(1,-2) =>str.substring(0,1) //a
2.slice(start starting position index, end (end position index) is basically similar to substring, the difference is that the parameter is a negative number.
var str='abcdefg'; str.slice(1) //bcdefg str.substring(1,3) // bc
When entering a negative value, the value is added to the length of the string
str.slice(-1) =>str.slice(6) //g
str.slice(1,-2) =>str.slice(1,5) //bcde
str.slice(-2,-1)=>str.slice(5,6) / When the absolute value of /f
is greater than the length of the string, it becomes 0
str.slice(-22) =>str.substring(0) //abcdefg
When the absolute value of the second parameter is greater than the length of the string, return ''
3.substr(start starting position index, end the number of characters to be returned)
var str='abcdefg'; str.substr(1) //bcdefg str.substr(1,1) //b
When a negative value is entered, the start parameter is added to the length of the string, and when the end is negative, the parameter becomes 0
str.substr(-1) =>str.substr(6)//g str.substr(-2,-3) // ''
4.charAt(index) method returns the value at the specified index position character. If the index value exceeds the valid range (0 and the length of the string minus one), an empty string is returned.
var str='abcdefg'; str.charAt(2) // c
5.index(string) Returns the first occurrence of a subcharacter in the String object string position. If the substring is not found, -1 is returned.
var str='abcdefga' str.indexOf('a') // 0 str.indexOf('h') //-1
6.lastIndexOf(string) Flashback search
Returns the position of the first substring occurrence in the String object. If the substring is not found, -1 is returned.
var str='abcdefga' str.lastIndexOf('a') // 7
7.split(str) Split the string into an array based on parameters
var str='abcadeafg' str.split('a') //["", "bc", "de", "fg"]
8. The toLowerCase method returns a string in which letters are converted to lowercase.
9. The toUpperCase method returns a string in which all letters are converted to uppercase letters.
10.match() – This method can search for a specified value within a string, or find a match for one or more regular expressions.
11.search Method returns the same as regular expression search The position of the first string whose content matches.
12.replace is used to find a string that matches a regular expression, and then replaces the match with a new string
http://www.cnblogs.com/bijiapo/p/5451924. html
Commonly used methods for arrays
1. push Add to the end Return the added array
2. Unshift Add to the front Return the added array
3. shift Delete (from the front) Return the processed array
4. pop Delete the last item Return the processed array
5. reverse Array flip Return the processed array
6. join Convert array into string
var arr=[1,2,3,4,5], str=arr.join('--'); console.log(str); // 1--2--3--4--5 以join内的参数切割数组 console.log(arr); // [1,2,3,4,5] 原数组未变
7. slice(start,end) Intercept array from start (start) to end (end not included)
Return to the new array, the original array is unchanged
var arr=[1,2,3,4,5],new=arr.slice(2,4); console.log(new); // [3,4] console.log(arr); // [1,2,3,4,5]
8. Concat array merged
9. Splice Array
(1). One parameter. Intercept the parameter position and fill in the negative number, similar to the str slice above. Return the intercepted array. The original array changes
var arr=[1,2,3,4,5]; console.log(arr.splice(1)); // [2,3,4,5] console.log(arr); // [1] console.lgo(arr.splice(-1)) // [5]
(2). Two Parameter interception (starting position, number) Return the intercepted array Original array change
var arr=[1,2,3,4,5]; console.log(arr.splice(1,3)); // [2,3,4] console.log(arr) // [1,5] arr.splice(0,1) =>arr.shift() arr.splcie(arr.length-1,1) =>arr.pop()
(3).Add Original array increase
var arr=[1,2,3,4,5]; console.log(arr.splice(1,0,13)); // [] console.log(arr); // [1,13,2,3,4,5]
(4). Replacement
var arr=[1,2,3,4,5]; console.log(arr.splice(1,2,'a','b')) // [2,3] console.log(arr); // [1,'a','b',4,5] arr.splice(0,0,1) =>arr.unshift(1); arr.splice(arr.length,0,1) => arr.push(1)
10. arr.forEach(item,index,array){} Traversal, loop similar to jquery's each
The item parameter is the content in the array, index is its index, and array represents the array itself
var arr=[1,2,3,4,5]; arr.forEach(function(item,index,array){ })
There is a problem when jumping out of a nested loop, which has not been solved yet;
11. map Methods Mapping usage is similar to forEach
var men=[ {'name':1,'age':12}, {'name':2,'age':22}, {'name':3,'age':33} ], age=men.map(function(item){ return item.age; })
12. arr.sort Sorting
var arr=[1,2,22,11,33,3,5,4]; console.log(arr.sort()) // [1,11,2,22,3,33,4,5]
By default the sort method is Sorted in ascii alphabetical order, not sorted by numerical size as we think
arr.sort(function(a,b){ return a-b})
a-b从小到大 b-a从大到小
13. 顺便写写我知道的排序方法
(1)冒泡排序 每次比较相邻的两个数,如果后一个数比前一个数小,换位置
function bSort(arr){ var tmp; for(var i=0,len=arr.length-1;i<len;i++){ for(var j=0;j<len;j++){ if(arr[j]>arr[j+1]){ //换位置 tmp=arr[j+1]; arr[j+1]=arr[j]; arr[j]=tmp; } } } return arr; } function bSort(arr){ var tmp; arr.forEach(function(item,i){ arr.forEach(function(item,i){ if(item>arr[i+1]){ //换位置 tmp = arr[i + 1]; arr[i + 1] = arr[i]; arr[i] = tmp; } }) }) return arr }
(2)快速排序 二分法,找到中间的数,取出来(新数组),原数组没,每次和此数比较,小的放到左边,大的放到右面
function fastSoft(arr){ var len=arr.length; if(len<=1){ return arr} var cIndex=Math.floor(len/2), c=arr.splice(c,1), left=[], right=[]; arr.forEach(function(item,i){ if(item<c[0]){ left.push(item); }else{ right.push(item); } }) return fastSoft(left).concat(c,fastSoft(right)); }
14. 数组的去重也写下吧
(1)双层循环不是很好
var arr=[2,3,2,2,2,4,5], arr2=[]; function find(arr2,ele){ for(var i= 0,len=arr2.length;i<len;i++){ if(arr2[i]==ele) return true; } return false; } for(var i= 0,len=arr.length;i<len;i++){ if(!find(arr2,arr[i])){ arr2.push(arr[i]); } }
(2)利用json的key值无重复
var arr=[2,3,2,2,2,4,5], json={}, arr2=[]; arr.forEach(function(item,i){ if(!json[item]){ json[item]=222; } }); for(var name in json){ arr2.push(Number(name));//类型发生变化了 }
(3) 利用sort方法排序,去掉旁边相同项
var arr=[2,3,2,4,4,4,5], arr2=[]; arr.sort(); for(var i=0;i<arr.length;i++){ if(arr[i]==arr[i+1]){ arr.splice(i--,1); } }
一些常见数学方法
math.abs() 取绝对值 math.ceil() 向上取整 math.floor() 向下取整 math.round() 四舍五入 math.roundom function getRan(n,m){ return Math.floor(Math.random()*(m-n)+n); }
数组和字符串的一些综合应用
1. 截取后缀名
(1) var str='1.xxx.avi';
str=str.substring(str.lastIndexOf('.')+1);
(2) var str='1.xxx.avi';
var arr=str.split('.'); console.log(arr[arr.length-1]);
2.字母翻转,首字母大写
var str='wo shi yi ge demo', arr=str.split(' '); for(var i=0;i<arr.length;i++){ console.log() arr[i]=arr[i].charAt(0).toUpperCase()+arr[i].substring(1); } arr.reverse(); str=arr.join(' ');
3. str中字符出现次数的统计
var str='aaaandkdffsfsdfsfssq12345', json={}, n= 0, sName; for(var i= 0,len=str.length;i<len;i++){ var Letter=str.charAt(i); //统计次数 if(json[Letter]){ json[Letter]++; }else{ json[Letter]=1; } } //找最大 for(var name in json){ if(json[name]>n){ n=json[name]; sName=name; } } console.log('出现最多的字母'+sName+'次数为'+n);
4. 简单的url参数解析
function getData() { var search = window.location.search.substring(1); if (!search) { return; } var arr = search.split('&'), arr2 = [], json = {}, key, alue; for (var i = 0; i < arr.length; i++) { arr2 = arr[i].split('='); key = arr2[0]; value = arr2[1]; json[key] = value; } return json; }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持PHP中文网!
更多js数组与字符串常用方法总结相关文章请关注PHP中文网!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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.

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


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

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

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