JavaScript arrays and Common function Details _ basics

Source: Internet
Author: User
Tags array sort numeric value object object

1. Understanding Arrays

An array is a collection of data of a type that can be integral, string, or even an object.
JavaScript does not support multidimensional arrays, but because arrays can contain objects (arrays are also objects), arrays can be nested to implement functions similar to multidimensional arrays.

1.1 Defining arrays

Declares an array of 10 elements:

Copy Code code as follows:
var a = new Array (10);

At this time for a has opened up the memory space, contains 10 elements, with the array name plus [subscript] to invoke, such as a[2] but at this time the element is not initialized, the call will return undefined.
The following code defines a mutable array and assigns the value.
Copy Code code as follows:

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

As mentioned above, you can put objects in an array, such as the following code:

Copy Code code 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 instantiated directly by assigning values, such as:

Copy Code code as follows:

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

A and B are all arrays, except that B uses an implicit declaration to create another instance, and if alert (a==b) pops up false

1.2 Multi-dimensional arrays

In fact, JavaScript is not supported multidimensional arrays, in the ASP can use Dim a (10,3) to define multidimensional array, in JavaScript, if the var a = new Array (10,3) will be the error
But as I said before, an array can contain objects, so you can declare an element in the array again as an array, for example:

Copy Code code as follows:

var a = new Array ();
A[0] = new Array ();
A[0][0] = 1;
Alert (a[0][0]); Pop up 1

Assignment when declaring a value
Copy Code code 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]];

As an effect, a takes a general instantiation, B is an implicit declaration, and the result is a multidimensional array.

1.3 Array Literals

I don't know how to call it in Chinese, what's the word array?
Speaking of arrays, we have to say array literals, arrays are actually special objects, objects have unique properties and methods, through the object name. Property, Object. Method () to take values and calls, while arrays are evaluated by subscript, array literals is similar to array, is a collection of data types, but array literals is essentially an object, declaration, and invocation, different from an array:

Copy Code code as follows:

var aa = new Object ();
aa.x = "Cat";
AA.Y = "Sunny";
alert (aa.x); Eject Cat

Create a Simple object, the general call is through the aa.x, and if as an array literals, with alert (aa["x"]) will pop the cat

Copy Code code as follows:

var a = {x: "Cat", Y: "Sunny"};
Alert (a["Y"]); Pop-up Sunny

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


2. Operation of array elements

As has been said above, you can read and write elements by array [subscript]
The scope of the subscript is 0– (23 (superscript 2)-1), when the subscript is negative, floating-point, or even Boolean, the array is automatically converted to the object type, for example:

Copy Code code as follows:

var B = new Array ();
b[2.2] = "XXXXX";
Alert (b[2.2]); -> XXXXX

At this time the equivalent of b["2.2"] = "XXXXX".

2.1 Loop of an array

Copy Code code as follows:

var a = [1,2,3,4,5,6];
for (var i =0; i<a.length; i++) {
Alert (A[i]);
}

This is the most commonly used, calendar array, and the code will pop 1 to 6 in turn.
There is also a common:
Copy Code code as follows:

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

or pop-up 1 to 6,for...in is a calendar object (an array is a special object) object, used on an array, because the array has no property name, so the direct output value, this structure statement is used on the object, for example:

Copy Code code as follows:

var a = {X:1,y:2,z:3};
for (Var e in a) {
Alert (E + ":" + a[e]);
}

At this point e takes the attribute name, that is x, Y, X, and to get the value, the array name [property] is used, so a[e] equals a["x", a["Y"], a["Z"]

2.2 Common functions for arrays


Concat

Append the array after the existing array and return the new array without affecting the existing array:

Copy Code code as follows:

var a = [123];
var b = "Sunnycat";
var c = ["www", "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

Note that you can only use an array or a string if you are connected (the preceding a) is a numeric value, Boolean value, the object, it will be the error, string connection array, string will be concatenated with the first element of the array to the new elements, and the array connection string will append new elements (this I do not know the cause of this, people who know, please disclose), For an array containing an array, an object, the connection remains intact.

Join

To connect an array to a string by using the specified spacer character:

Copy Code code as follows:

var a = [' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' G '];
Lert (A.join (",")); -> a,b,c,d,e,f,g 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 is important to note that only a one-dimensional array is converted, and if there is an array in the array, it is not followed by the string specified by the join, but rather by the default ToString (), for example

Copy Code code 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: Array inside array, no use * connection

Pop

Deletes the last element of the array and returns the element

Copy Code code as follows:

var a = ["AA", "BB", "CC"];
document.write (A.pop ()); -> cc
document.write (a); -> AA, BB

Note: If the array is empty, return undefined

Push

Adds an array to the back of the array and returns the new length of the array

Copy Code code 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 the concat does not affect the original array, returns the new array directly, and the push modifies the original array, returning the new length of the array.

Sort

Array sort, first look at an example

Copy Code code as follows:

var a = [11,2,3,33445,5654,654, "ASD", "B"];
Alert (A.sort ()); -> 11,2,3,33445,5654,654,asd,b

The result is not very unexpected, yes, the sort is not according to the size of the integer, but the string contrast, is to take the first character of the ANSI code contrast, small row front, the same words to take the second ratio, if you want to compare the integer value, you can

Copy Code code 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 a function in the code, which is a simple example of not being able to sort the non-numeric, not the number that needs to be judged, not much.

Reverse

The array is reversed and, sort (), the first character ASCII value is compared

Copy Code code as follows:

var a = [11,3,5,66,4];
Alert (A.reverse ()); -> 4,66,5,3,11

If the array contains an array, it is treated as an object and does not solve the element

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

It's supposed to be the last 11 row, because it compares 4,11,33 as a complete object, so it's ranked first.
If you can't see it, string it up with a join () and you'll know more

Shift

Deletes the first element of the array and returns the element, similar to pop

Copy Code code as follows:

var a = ["AA", "BB", "CC"];
document.write (A.shift ()); -> AA
document.write (a); -> BB,CC

Note: When the array is empty, return undefined

Unshift

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

Copy Code code as follows:

var a = ["AA", "BB", "CC"];
document.write (A.unshift (11)); -> 4 Note: ie return 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 the method, in IE will return to undefined, seemingly Microsoft bug, I under Firefox can play the array of new length correctly

Slice

Returns an array fragment

Copy Code code 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), starting with subscript 1, to the number of subscript 2, note that the element with subscript 2 is not included
If there is only one argument, the default to array is the last
-4 is the 4th element of the penultimate, so it returns the reciprocal four elements.
The last line, starting from the penultimate 2nd, because it is truncated later, obviously does not take the previous element, so return an empty array, and if changed to A.slice ( -6,-2) then return b,c,d,e

Splice

Deletes an element of a fragment from an array and returns the deleted element

Copy Code code 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: IE return empty
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 the method in IE, the second parameter is required, do not fill the default is 0, such as A.splice (4), in IE returned empty, the effect is equivalent to A.splice (4,0)

Tostring

Convert an array to a string, not just an array, all objects can use this method

Copy Code code 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, and the object returns [object objectname]
Join () replaces only one-dimensional arrays, compared to the join () method, and ToString () completely flatten the entire array, whether one-dimensional or multidimensional.
At the same time, this method can be used in 10, 2, 8, 16-conversion, for example:

Copy Code code as follows:

var a = [5,6,7,8,9, "a", "BB", 100];
for (var i=0; i<a.length; i++) {
document.write (a[i].tostring () + "binary is" + a[i].tostring (2) + ", octal is" + a[i].tostring (8) + ", Hex is" + A[i].tos  Tring (16)); -> 4,5
}

Output results:
Copy Code code as follows:

5 binary is 101, octal is 5, Hex is 5
6 binary is 110, octal is 6, Hex is 6
7 binary is 111, octal is 7, Hex is 7
8 binary is 1000, octal is 10, Hex is 8
9 binary is 1001, octal is 11, Hex is 9
The binary of A is a, octal is a, and hexadecimal is a.
BB's binary is bb, octal is bb, Hex is BB
100 binary is 1100100, octal is 144, Hex is 64

The conversion can only be done in the element, and if the entire array is converted, the array is returned intact

toLocaleString

Returns a local format string, primarily used on a Date object

Copy Code code 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 17:28:36
document.write (A.tolocaledatestring ()); -> August 8, 2009

The difference is that toString () returns to the standard format, tolocalestring () returns the local format full date (in Control Panel >> Regional and Language Options, by modifying [time] and [Long Date] formats), tolocaledatestring () like toLocaleString (), just a little time.

valueof

The output is similar to ToString (), but ToString () returns the string type and valueof () returns the original object type, depending on the original value returned by different objects.

Copy Code code 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

The array is also an object, so typeof (A.valueof ()) returns object, and the return is still a multidimensional array

Copy Code code 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 from January 1, 1970, and the math and Error objects do not have valueof methods.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.