Home Web Front-end JS Tutorial Summary of some commonly used array function usage examples in JavaScript

Summary of some commonly used array function usage examples in JavaScript

Jul 25, 2017 am 11:52 AM
javascript js function

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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 array

var 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
Copy after login

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

var a = [11,2,3,33445,5654,654,"asd","b"];
alert(a.sort()); // -> 11,2,3,33445,5654,654,asd,b
Copy after login

Isn’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,33445
Copy after login

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

var a = [11,3,5,66,4];
alert(a.reverse());  // -> 4,66,5,3,11
Copy after login

If 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 * a
Copy after login

Logically, 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 pop

var a =    ["aa","bb","cc"];
document.write(a.shift());   // -> aa
document.write(a);        // -> bb,cc
Copy after login

Note: 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 array

var 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
Copy after login

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

var 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));    // -> 空
Copy after login

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.

#splice

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
Copy after login

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)

toString

Convert 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); }
Copy after login

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
}
Copy after login

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
Copy after login

Conversion can only be performed on elements. If the entire array is converted, the array will be returned unchanged

toLocaleString

Returns 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日
Copy after login

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

valueOf

Returns 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
Copy after login

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
Copy after login

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!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tips for dynamically creating new functions in golang functions Tips for dynamically creating new functions in golang functions Apr 25, 2024 pm 02:39 PM

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.

Considerations for parameter order in C++ function naming Considerations for parameter order in C++ function naming Apr 24, 2024 pm 04:21 PM

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.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

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.

How to write efficient and maintainable functions in Java? How to write efficient and maintainable functions in Java? Apr 24, 2024 am 11:33 AM

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

Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Comparison of the advantages and disadvantages of C++ function default parameters and variable parameters Apr 21, 2024 am 10:21 AM

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.

What are the benefits of C++ functions returning reference types? What are the benefits of C++ functions returning reference types? Apr 20, 2024 pm 09:12 PM

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.

What is the difference between custom PHP functions and predefined functions? What is the difference between custom PHP functions and predefined functions? Apr 22, 2024 pm 02:21 PM

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.

C++ Function Exception Advanced: Customized Error Handling C++ Function Exception Advanced: Customized Error Handling May 01, 2024 pm 06:39 PM

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.

See all articles