


Summary of some commonly used array function usage examples in JavaScript
Common functions for arrays
concat
Append an array after the existing array and return the new array without affecting the existing array:
var a = [123]; var b = "sunnycat"; var c = ["www",21,"ido"]; var d = {x:3.14, y:"SK"}; var e = [1,2,3,4,[5,6,[7,8]]]; alert(a.concat(b)); // -> 123,sunnycat alert(a); // -> 123 alert(b.concat(c, d)); // -> sunnycatwww,21,ido[object Object] alert(c.concat(b)); // -> www,21,ido,sunnycat alert(e.concat(11,22,33).join(" # ")); // -> 1 # 2 # 3 # 4 # 5,6,7,8 # 11 # 22 # 33
It should be noted that it can only be used for arrays or strings. If what is connected (the previous a) is a numerical value, Boolean value, or object, an error will be reported. When a string is connected to an array, the string will It is spliced with the first element of the array to form a new element, and the array connection string will append the new element (I don’t know the reason for this, please disclose if you know the truth). For arrays containing arrays and objects, they will remain intact after the connection.
join
Connect the arrays with specified separators and convert the arrays into strings:
var a = ['a','b','c','d','e','f','g']; lert(a.join(",")); // -> a,b,c,d,e,f,g 相当于a.toString() alert(a.join(" x ")); // -> a x b x c x d x e x f x g
This is easy to understand, but you need to pay attention to Only the one-dimensional array is converted. If there is an array in the array, the string connection specified by join will not be used, but the default toString() will be used, such as
var a = ['a','b','c','d','e','f','g',[11,22,33]]; alert(a.join(" * ")); // -> a * b * c * d * e * f * g * 11,22,33
Note: The array in the array does not Use * to connect
pop
Delete the last element of the array and return the element
var a = ["aa","bb","cc"]; document.write(a.pop()); // -> cc document.write(a); // -> aa, bb
Note: If the array is empty, undefined# is returned
##push
Add an array to the end of the array and return the new length of the arrayvar a = ["aa","bb","cc"]; document.write(a.push("dd")); // -> 4 document.write(a); // -> aa,bb,cc,dd document.write(a.push([1,2,3])); // -> 5 document.write(a); // -> aa,bb,cc,dd,1,2,3The difference with concat is that concat does not affect the original array and returns it directly New array, while push directly modifies the original array, returning the new length of the array
sort
Array sorting, let’s look at an example firstvar a = [11,2,3,33445,5654,654,"asd","b"]; alert(a.sort()); // -> 11,2,3,33445,5654,654,asd,bIsn’t the result surprising? Yes, the sorting is not based on integer size, but on string comparison. That is to compare the ANSI code of the first character. The smaller one is ranked first. If they are the same, the second character is compared. If To compare by integer values, you can do this
var a = [11,2,3,33445,5654,654]; a.sort(function(a,b) { return a - b; }); alert(a); // -> 2,3,11,654,5654,33445The sort() method has an optional parameter, which is the function in the code. This is a simple example. Non-numbers cannot be sorted. Non-numbers need to be done more. Judgment, I won’t talk much here
reverse
Reverse sorting of the array is the same as sort(), taking the ASCII value of the first character for comparisonvar a = [11,3,5,66,4]; alert(a.reverse()); // -> 4,66,5,3,11If the array also contains an array, it will be treated as an object and the elements will not be solved.
var a = ['a','b','c','d','e','f','g',[4,11,33]]; alert(a.reverse()); // -> 4,11,33,g,f,e,d,c,b,a alert(a.join(" * ")); // -> 4,11,33 * g * f * e * d * c * b * aLogically, it should be the last row of 11, because here 4, 11, 33 are regarded as complete objects. Compare, so it is ranked first
If you don’t understand, use join() to string it together, and it will be clearer
shift
Delete the first place in the array element, and returns the element, which is similar to popvar a = ["aa","bb","cc"]; document.write(a.shift()); // -> aa document.write(a); // -> bb,ccNote: When the array is empty, undefined is returned
unshift
The opposite of shift , add elements to the front of the array, and return the new length of the arrayvar a = ["aa","bb","cc"]; document.write(a.unshift(11)); // -> 4 注:IE下返回undefined document.write(a); // -> 11,aa,bb,cc document.write(a.unshift([11,22])); // -> 5 document.write(a); // -> 11,22,11,aa,bb,cc document.write(a.unshift("cat")); // -> 6 document.write(a); // -> cat,11,22,11,aa,bb,ccNote that this method will return undefined under IE, which looks like a Microsoft bug, but I can correctly display the new length of the array under Firefox
slice
Return array fragmentvar a = ['a','b','c','d','e','f','g']; alert(a.slice(1,2)); // -> b alert(a.slice(2)); // -> c,d,e,f,g alert(a.slice(-4)); // -> d,e,f,g alert(a.slice(-2,-6)); // -> 空a.slice(1,2), starting from subscript 1 to subscript 2 Number, please note that it does not include the element with subscript 2
If there is only one parameter, it defaults to the end of the array
-4 means the fourth element from the bottom, so the four elements from the bottom are returned
The last line , starting from the second to last, because it is intercepted backward, so obviously the previous elements cannot be obtained, so an empty array is returned. If it is changed to a.slice(-6,-2), b,c,d,e## will be returned.
Delete an element of a fragment from the array and return the deleted element
var a = [1,2,3,4,5,6,7,8,9]; document.write(a.splice(3,2)); // -> 4,5 document.write(a); // -> 1,2,3,6,7,8,9 document.write(a.splice(4)); // -> 7,8,9 注:IE下返回空 document.write(a); // -> 1,2,3,6 document.write(a.splice(0,1)); // -> 1 document.write(a); // -> 2,3,6 document.write(a.splice(1,1,["aa","bb","cc"])); // -> 3 document.write(a); // -> 2,aa,bb,cc,6,7,8,9 document.write(a.splice(1,2,"ee").join("#")); // -> aa,bb,cc#6 document.write(a); // -> 2,ee,7,8,9 document.write(a.splice(1,2,"cc","aa","tt").join("#")); // -> ee#7 document.write(a); // -> 2,cc,aa,tt,8,9
Note that this method is under IE, the second parameter is required If not filled in, it defaults to 0. For example, a.splice(4) will return empty under IE. The effect is equivalent to a.splice(4,0)
toStringConvert an array to a string, not just arrays, but all objects can use this method
var a = [5,6,7,8,9,["A","BB"],100]; document.write(a.toString()); // -> 5,6,7,8,9,A,BB,100 var b = new Date() document.write(b.toString()); // -> Sat Aug 8 17:08:32 UTC+0800 2009 var c = function(s){ alert(s); } document.write(c.toString()); // -> function(s){ alert(s); }
Boolean values return true or false, objects return [object objectname]
Compared with join( ) method, join() only replaces a one-dimensional array, while toString() completely flattens the entire array (whether one-dimensional or multi-dimensional).At the same time, this method can be used for decimal, binary, and octal systems. System and hexadecimal conversion, for example:
var a = [5,6,7,8,9,"A","BB",100]; for(var i=0; i<a.length; i++){ document.write(a[i].toString() + " 的二进制是 " + a[i].toString(2) + " ,八进制是 " + a[i].toString(8) + " ,十六进制是 " + a[i].toString(16)); // -> 4,5 }
Output result:
5 的二进制是 101 ,八进制是 5 ,十六进制是 5 6 的二进制是 110 ,八进制是 6 ,十六进制是 6 7 的二进制是 111 ,八进制是 7 ,十六进制是 7 8 的二进制是 1000 ,八进制是 10 ,十六进制是 8 9 的二进制是 1001 ,八进制是 11 ,十六进制是 9 A 的二进制是 A ,八进制是 A ,十六进制是 A BB 的二进制是 BB ,八进制是 BB ,十六进制是 BB 100 的二进制是 1100100 ,八进制是 144 ,十六进制是 64
Conversion can only be performed on elements. If the entire array is converted, the array will be returned unchanged
toLocaleStringReturns a local format string, mainly used on Date objects
var a = new Date(); document.write(a.toString()); // -> Sat Aug 8 17:28:36 UTC+0800 2009 document.write(a.toLocaleString()); // -> 2009年8月8日 17:28:36 document.write(a.toLocaleDateString()); // -> 2009年8月8日
The difference is that toString() returns the standard format and toLocaleString() returns the local format Format the complete date (in [Control Panel]>>[Regional and Language Options], by modifying the [Time] and [Long Date] formats), toLocaleDateString() is the same as toLocaleString(), except that the time is missing
valueOfReturns different original values according to different objects. When used for output, it is similar to toString(), but toString() returns the string type, while valueOf() returns the original object. Type
var a = [1,2,3,[4,5,6,[7,8,9]]]; var b = new Date(); var c = true; var d = function(){ alert("sunnycat"); }; document.write(a.valueOf()); // -> 1,2,3,4,5,6,7,8,9 document.write(typeof (a.valueOf())); // -> object document.write(b.valueOf()); // -> 1249874470052 document.write(typeof(b.valueOf())); // -> number document.write(c.valueOf()); // -> true document.write(typeof(c.valueOf())); // -> boolean document.write(d.valueOf()); // -> function () { alert("sunnycat"); } document.write(typeof(d.valueOf())); // -> function
Arrays are also objects, so typeof (a.valueOf()) returns object, which is still a multi-dimensional array
var a = [1,2,3,[4,5,6,[7,8,9]]]; var aa = a.valueOf(); document.write(aa[3][3][1]); // -> 8
The Date object returns the distance from January 1, 1970 Milliseconds, Math and Error objects do not have a valueOf method.
The above is the detailed content of Summary of some commonly used array function usage examples in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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.

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.


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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

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