Home  >  Article  >  Web Front-end  >  Detailed explanation of JavaScript arrays and common functions_Basic knowledge

Detailed explanation of JavaScript arrays and common functions_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:49:021103browse

1. Get to know arrays

An array is a collection of certain types of data. The data type can be integer, string, or even object.
Javascript does not support multi-dimensional arrays, but because arrays can contain objects (an array is also an object), arrays can achieve functions similar to multi-dimensional arrays by nesting each other.

1.1 Define array

Declare an array with 10 elements:

Copy the code The code is as follows:
var a = new Array(10);

At this time, the memory space has been opened for a, containing 10 elements. Use the array name plus [subscript] to call it, such as a[2], but the element has not been initialized at this time. The call will return undefined.
The following code defines a variable array and assigns values.
Copy code The code is as follows:

var a = new Array();
a [0] = 10;
a[1] = "aaa";
a[2] = 12.6;

As mentioned above, objects can be placed in arrays, for example, the following code:

Copy code The code is as follows:

var a = new Array();
a[0] = true;
a[1] = document.getElementById("text");
a[2] = { x:11, y:22};
a[3] = new Array();

Arrays can also be assigned values ​​directly when instantiated, for example:

Copy code The code is as follows:

var a = new Array(1, 2, 3, 4, 5);
var b = [1, 2, 3, 4, 5];

a and b are both arrays, but b uses an implicit declaration to create another instance. At this time, if alert(a==b) is used, false

will pop up

1.2 Multidimensional Array

Actually, Javascript does not support multi-dimensional arrays. In asp, you can use dim a(10,3) to define multi-dimensional arrays. In Javascript, if you use var a = new Array(10,3), an error will be reported
But as mentioned before, arrays can contain objects, so you can declare an element in the array as an array, for example:

Copy code The code is as follows:

var a = new Array();
a [0] = new Array();
a[0][0] = 1;
alert(a[0][0]); //Pop up 1

statement When assigning
Copy code The code is as follows:

var a = new Array([1, 2,3], [4,5,6],[7,8,9]);
var b = [[1,2,3], [4,5,6], [7,8, 9]];

The effect is the same, a uses regular instantiation, b is an implicit declaration, and the result is a multi-dimensional array.

1.3 Array literals

I really don’t know what this is called in Chinese, text array?
Speaking of arrays, we have to talk about Array Literals. Arrays are actually special objects. Objects have unique properties and methods. Values ​​and calls are obtained through object name.property, object.method(), and arrays are obtained through the following Mark to get the value. Array Literals are similar to arrays in many ways. They are both collections of a certain data type. However, Array Literals is fundamentally an object. Its declaration and call are different from arrays:

Copy code The code is as follows:

var aa = new Object();
aa .x = "cat";
aa.y = "sunny";
alert(aa.x); //Pop up cat

Create a simple object. Generally, the call is through aa.x. If it is used as Array literals, using alert(aa["x"]) will also pop up cat

Copy code The code is as follows:

var a = {x: "cat", y: "sunny"};
alert(a["y"]); //pop up sunny

This is another way to create an object, the result is the same


2. Operation of array elements

As mentioned above, you can read and write elements through array [subscript]
The range of the subscript is 0 – (23 (superscript 2) -1), and the subscript is a negative number, floating point or even a Boolean value time, the array will be automatically converted to the object type, for example:

Copy code The code is as follows:

var b = new Array();
b[2.2] = "XXXXX";
alert(b[2.2]); //-> XXXXX

This is equivalent to b["2.2"] = "XXXXX".

2.1 Array loop

Copy code The code is as follows:

var a = [1,2,3,4,5,6];
for(var i =0; ialert(a[i]);
}

This is the most commonly used one. After traversing the array, the code will pop up 1 to 6 in sequence
There is another commonly used one:
Copy code The code is as follows:

var a = [1,2,3,4,5,6];
for(var e in a){
alert(e);
}

Still pops up 1 to 6 in sequence. for...in is a traversal object (array is a special object) object. It is used on an array. Because the array has no attribute name, the value is output directly. This structural statement is used on the object. For example:

Copy code The code is as follows:

var a = {x:1,y :2,z:3};
for(var e in a){
alert(e ":" a[e]);
}

At this time, e gets the attribute name, that is, x, y, x. To get the value, the array name [attribute] is used, so a[e] is equivalent to a["x"], a[" y”], a[“z”]

2.2 Common array functions


concat

Appends an array after the existing array and returns the new array without affecting the existing array:

Copy code The code is as follows:

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 the connection (a in front) is a numerical value, Boolean value, or object, an error will be reported. When a string is connected to an array, the string will be followed by the first element of the array. Splicing into new elements, while the array connection string will append new elements (I don't know the reason for this, please disclose if you know). For arrays containing arrays and objects, they will remain intact after connection.

join

Concatenate the arrays with specified separators and convert the arrays into strings:

Copy the code The code is as follows:

var a = ['a','b','c','d','e','f','g'];
lert(a.join("," )); // -> a,b,c,d,e,f,g are equivalent to 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 it should be noted that only one-dimensional arrays are converted. If there are arrays in the array, the string connection specified by join will not be used, but the default toString() will be used, such as

Copy code The code is as follows:

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 inside the array is not used for * connection

pop

Delete the last element of the array and return the element

Copy code The code is as follows:

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

Copy code The code is as follows:

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 directly returns a new array, while push directly modifies the original array and returns the new length of the array

sort

Array sorting, let’s look at an example first

Copy code The code is as follows:

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 by integer size, but by string comparison. That is to compare the ANSI code of the first character. The smaller one is ranked first. If it is the same, the second character is taken and then Ratio, if you want to compare by integer values, you can do this

Copy code The code is as follows:

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 require more judgment, so I won’t go into details here

reverse

Reverse sorting of the array is the same as sort(), taking the ASCII value of the first character for comparison

Copy code Code As follows:

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 extracted

Copy code Code As follows:

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 at the end of row 11, because 4, 11, 33 are compared here as complete objects, so they are ranked first
If you don’t understand, use join() to string them together, and it will be much clearer.

shift

Delete the first element of the array and return the element, which is similar to pop

Copy code The code is as follows:

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

In contrast to shift, add elements to the front of the array and return the new length of the array

Copy code The code is as follows:

var a = ["aa","bb","cc"];
document.write(a.unshift(11)); // -> 4 Note: Returns undefined in IE
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 seems to be a Microsoft bug. I can correctly use the new length of the array under Firefox

slice

Return array fragment

Copy code The code is as follows:

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

a.slice(1,2), the number starting from subscript 1 to subscript 2, note that the element with subscript 2 is not included
If there is only one parameter, it defaults to The last
-4 of the array represents the 4th element from the bottom, so the four elements from the bottom are returned. The last row of
starts from the 2nd from the bottom. Because it is intercepted backward, it is obvious that the previous elements cannot be obtained, so Returns an empty array. If changed to a.slice(-6,-2), it returns b,c,d,e

splice

Delete an element of a fragment from the array and return the deleted element

Copy code The code is as follows:

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 Note: Under IE, an empty
document is returned. 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 the second parameter of this method is required under IE. If not filled in, it defaults to 0, such as a.splice(4). Under IE, it returns empty, and the effect is equivalent to a.splice(4,0 )

toString

Convert arrays to strings, not just arrays, but all objects can use this method

Copy code The code is as follows:

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 value returns true or false, object returns [object objectname]
Compared with join() method, join() only replaces one-dimensional array, while toString() replaces the entire array (regardless of one-dimensional array). Dimensional or multi-dimensional) completely flat
At the same time, this method can be used for decimal, binary, octal, and hexadecimal conversion, for example:

Copy Code The code is as follows:

var a = [5,6,7,8,9,"A","BB",100];
for(var i=0; idocument.write(a[i].toString() " The binary system is " a[i].toString(2) " and the octal system is " a[i].toString(8) ", hexadecimal is " a[i].toString(16)); // -> 4,5
}

Output result:
Copy code The code is as follows:

The binary of 5 is 101, The octal system is 5, the hexadecimal system is 5
The binary system of 6 is 110, the octal system is 6, the hexadecimal system is 6
The binary system of 7 is 111, the octal system is 7, and the hexadecimal system is 7
The binary system of >8 is 1000, the octal system is 10, and the hexadecimal system is 8. The binary system of
9 is 1001, the octal system is 11, and the hexadecimal system is 9. The binary system of A
A is A, the octal system is A, and the decimal system is A Hexadecimal is A
BB, binary is BB, octal is BB, and hexadecimal is BB
100 is 1100100 in binary, octal is 144, and hexadecimal is 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

Copy code The code is as follows:

var a = new Date();
document .write(a.toString()); // -> Sat Aug 8 17:28:36 UTC 0800 2009
document.write(a.toLocaleString()); // -> August 8, 2009 Date 17:28:36
document.write(a.toLocaleDateString()); // -> August 8, 2009

The difference is that toString() returns the standard format, and toLocaleString() returns the complete date in the local format (in [Control Panel]>>[Regional and Language Options], by modifying the [Time] and [Long Date] formats) , toLocaleDateString() is the same as toLocaleString(), but it takes less time

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

Copy code The code is as follows:

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

Copy code The code is as follows:

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 number of milliseconds since January 1, 1970. The Math and Error objects do not have the valueOf method.

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