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

Summary of some commonly used array function usage examples in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-25 11:52:291226browse

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

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

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

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

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

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

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

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));    // -> 空

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

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); }

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

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日

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

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!

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