


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,3
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,b
var a = [11,2,3,33445,5654,654]; a.sort(function(a,b) { return a - b; }); alert(a); // -> 2,3,11,654,5654,33445
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,11
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 * a
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,cc
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,cc
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)); // -> 空
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!

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.

The benefits of functions returning reference types in C++ include: Performance improvements: Passing by reference avoids object copying, thus saving memory and time. Direct modification: The caller can directly modify the returned reference object without reassigning it. Code simplicity: Passing by reference simplifies the code and requires no additional assignment operations.

The difference between custom PHP functions and predefined functions is: Scope: Custom functions are limited to the scope of their definition, while predefined functions are accessible throughout the script. How to define: Custom functions are defined using the function keyword, while predefined functions are defined by the PHP kernel. Parameter passing: Custom functions receive parameters, while predefined functions may not require parameters. Extensibility: Custom functions can be created as needed, while predefined functions are built-in and cannot be modified.

Exception handling in C++ can be enhanced through custom exception classes that provide specific error messages, contextual information, and perform custom actions based on the error type. Define an exception class inherited from std::exception to provide specific error information. Use the throw keyword to throw a custom exception. Use dynamic_cast in a try-catch block to convert the caught exception to a custom exception type. In the actual case, the open_file function throws a FileNotFoundException exception. Catching and handling the exception can provide a more specific error message.
