Use of javascript Arrays

Source: Internet
Author: User
Tags array definition javascript array

In js, arrays have many operations, including array creation, sorting, length, value, deletion, access, and other data operation methods. Below I will summarize js Array Operations, for more information, see.

Js array definition:

The Code is as follows: Copy code

Method 1.

Var mycars = new Array ()
Mycars [0] = "Saab"
Mycars [1] = "Volvo"
Mycars [2] = "BMW"

Method 2.

Definition and initialization together:

Var mycars = new Array ("Saab", "Volvo", "BMW ")

Or another method:

Var mycars = ["Saab", "Volvo", "BMW"];


2. Access to array elements

 

The Code is as follows: Copy code

 

Var testGetArrValue = arrayObj [1]; // obtain the element value of the array.

ArrayObj [1] = "this is a new value"; // assign a new value to the array element
 

 

3. Add array elements

 

The Code is as follows: Copy code

 

ArrayObj. push ([item1 [item2 [... [itemN]); // Add one or more new elements to the end of the array and return the new length of the array.

ArrayObj. unshift ([item1 [item2 [... [itemN]); // adds one or more new elements to the array. The elements in the array are automatically removed and the new length of the array is returned.

ArrayObj. splice (insertPos, 0, [item1 [, item2 [,... [, itemN]); // insert one or more new elements to the specified position of the array. The inserted element is automatically removed and "" is returned "".

 

 

4. Deletion of array elements

 

The Code is as follows: Copy code

 

ArrayObj. pop (); // removes the last element and returns the value of this element.

ArrayObj. shift (); // removes the first element and returns the element value. The elements in the array are automatically moved forward.

ArrayObj. splice (deletePos, deleteCount );


// Delete the specified number of deleteCount elements starting from deletePos in the specified position. The removed elements are returned in the array format.

 

5. truncate and merge Arrays

 

The Code is as follows: Copy code

 

ArrayObj. slice (start, [end]);

// Return part of the array in the form of an array. Note that the end element is not included. If the end element is omitted, all elements after start will be copied.

ArrayObj. concat ([item1 [, item2 [,... [, itemN]);

// Concatenates multiple arrays (or strings, or arrays and strings) into an array and returns a new connected array.
 

 
6. Copy an array

 

The Code is as follows: Copy code

 

ArrayObj. slice (0); // returns the copy array of the array. Note that it is a new array, not pointing

ArrayObj. concat (); // returns the copy array of the array. Note that it is a new array, not pointing

Javascript two-dimensional array:

Javascript uses a one-dimensional array to simulate a two-dimensional array:

Method 1.

Var arr = new Array (['A', 'B', 'C'], ['D', 'E', 'F']);
Arr [0] returns the first one-dimensional array, and arr [0] [0] returns the first element 'a' of the first one-dimensional array, the same below.

Method 2.

Arr = new Array ();
For (I = 0; I <100; I ++ ){
Arr [I] = new Array (...);
}

Method 3.

Var arr = new Array (
New Array (),
New Array (),
New Array ()
);

 

Maximum data search Value


Code

The Code is as follows: Copy code

Function array_max ()

{

Var I,
Max = this [0];

For (I = 1; I <this. length; I ++)

{

If (max <this [I])

Max = this [I];


}

Return max;


}

Array. prototype. max = array_max;

Var x = new Array (1, 2, 3, 4, 5, 6 );

Var y = x. max ();


Array length:

You do not need to set the length of the javascript array. The array name. length returns the number of elements.

Code

The Code is as follows: Copy code

Var arr = [,];

// Defines an array containing 10 numbers

Alert (arr. length); // display the length of the array by 10

Arr. length = 12; // increase the length of the array.

Alert (arr. length); // display that the length of the array has changed to 12

Alert (arr [8]); // displays the value of the 9th elements, 56

Arr. length = 5; // reduce the length of the array to 5. elements whose index is equal to or greater than 5 are discarded.

Alert (arr [8]); // display that 9th elements have changed to "undefined"

Arr. length = 10; // restore the array length to 10

Alert (arr [8]); // although the length is restored to 10, 9th elements cannot be recovered, and "undefined" is displayed"

Common functions:

Array common functions

ToString (): converts an array into a string.
ToLocaleString (): converts an array into a string.
Join (): converts an array into a string connected with symbols.
Shift (): removes an element from the array header.
Unshift (): insert an element in the header of the array.
Pop (): deletes an element from the end of the array.
Push (): Add an element to the end of the array.
Concat (): add elements to the array
Slice (): returns the part of the array
Reverse (): sorts arrays in reverse order.
Sort (): sorts arrays.
Splice (): insert, delete, or replace an array element.

 

Javascript array sorting:

Arrayobj. sort (sortfunction)

Parameters

ArrayObj
Array
SortFunction
Optional. Comparison functions. If this parameter is omitted, the elements are listed in ascending order of ASCII characters.
The comparison function must return one of the following values:

* Negative value. If the first parameter is smaller than the second parameter.
* Zero. If the two parameters are equal.
* Positive value. If the first parameter is greater than the second parameter

Example:

The Code is as follows: Copy code

Var testArray = [1, 5, 2, 3, 6, 4]
TestArray. sort (function (a, B) {return a-B ;});
Alert (testArray );

Array usage Summary

The Code is as follows: Copy code


<Script language = "javascript">

/*
Javascript is a non-type language, so an array element can have any data type, different elements of the same Array
The array element settings can contain other arrays, so that you can create a complex array.
At this point, javascript, as a scripting language, is different from the strict object-oriented c ++. c # And java. It has higher flexibility.
*/

/*
* In javascript1.1 and later versions, arrays are created using constructor Array () and operator new,
The following three methods can be used to create arrays in javascript.
*/
Var a = new Array ();
Var B = new Array (5, 4, 3, "first", "test, string ");
Var c = new Array (20 );

A [1.23] = "test ";
Document. write ("a [1.23] =" + a [1.23]);
// I believe that every person who learns javascript from a strong programming language will be surprised by the above operations,
// Float data is also used as the subscript of the array. In fact, it is not as you think.
// Javascript converts a negative number, floating point number (or Boolean, object, or other value) to a string.
// Use the generated string as the property name of the object, instead of defining a new array element.
// The above instance is actually creating an attribute named "1.23" for.
Document. write ("a. length =" + a. length );
Document. write ("B. length =" + B. length );
Document. write ("c. length =" + c. length );

A [3] = "Test ";
Document. write ("<br/> a [3] =" + a [3]);
Document. write ("<br/> a. length =" + a. length );
// The above test also makes it clear that we use an integer as the subscript of the array to actually add an element to the array,
// Here the length of the array is used to reflect the mysteries of the javascript array.


// The length of the array can be truncated by setting the length attribute of the array.
A. length = 3;
If (a [3] = undefined)
{
Document. write ("<br/> after a. length =" + a. length + ", a [3] =" + a [3]);
}
Else
{
Document. write ("<br/> after a. length =" + a. length + ", a [3] =" + a [3]);
}

// Test our multi-dimensional array element here
/*
* In javascript, multi-dimensional arrays are not supported.
* However, we assign the elements of a one-dimensional array to another one-dimensional array, which seems to implement a multi-dimensional array,
In fact, he is still a one-dimensional array, which is the same idea as we understand arrays in C language, but their implementation mechanism is different.
*/
Var g = new Array (3 );
G [3] =;
G [3] [2] = "Test"
Document. write ("<br/> g [3] [2] =" + g [3] [2]);

// Array join () method
For (var I = 0; I <20; I ++)
{
C [I] = I;
Document. write ("<br/> c [I] =" + c [I]);
}
Document. write ("<br/> after the Element join () method of c is:" + c. join ());
// Reverse () method of the array
C. reverse ();
The result of the document. write ("<br/> c element after the reverse () method and then join () is:" + c. join ("| "));

// Test the concat () method
Var h = new Array (1, 2, 3 );
H = h. concat ([4, 5]);
// But the concat function does not recursively expand an array whose elements are arrays.
H = h. concat (6, 7, [9, [10, 20]);
Document. write ("<br/> h. length =" + h. length + "<br/>" + h );
Document. write ("h [8] =" + h [8]);


// Slice () method
Document. write ("<br> h. slice (4,5) =" + h. slice (4,5 ));
Document. write ("h. slice (5, 9) =" + h. slice (5, 9 ))
// Slice () method: the returned array contains the element specified by the first parameter and the element specified by the second parameter.
// The element that ends with the element but does not contain the element specified by the second parameter.


// Splice () method
// The splice () method is a common method used to insert or delete array elements.
/*
The first parameter of the splice function specifies the position of the element to be inserted or deleted in the array.
The second parameter specifies the number of elements to be deleted from the array.
After the second parameter, there can be any number of parameters that specify the elements inserted from the position specified by the first parameter.
Move the first element and subsequent elements accordingly.
*/

Document. write ("<br/> h. After splice (8, 1), h is:" + h. splice (8, 1 ));
// Document. write ("<br/> h. h after splice (8, 0, 'A', 'B', 'test') is: "+ h. splice (8, 0, 'A', 'B', 'test '));
H. splice (7,0, 'A', 'B', 'test ');
Document. write ("<br/> h. splice (, 'A', 'B', 'test') after h:" + h );


// The array in javascript is used as a stack and is similar to that in php.
// This is more interesting and useful.
// The following is a small instance used as a stack
/*
The push method attaches one or more new elements to the end of the array and returns the new length of the array.
Pop will delete the last element of the array, stick to the length of the array, and return the deleted Value.
*/
Var stack = new Array ();
Stack. push (1, 2 );
Document. write ("<br> the stack element is:" + stack );
Document. write ("<br/> stack. length =" + stack. length );
Document. write ("<br> the result returned by stack. pop () is:" + stack. pop ());
Document. write ("<br/> stack. length =" + stack. length );

// The following is a small instance used as a queue
/*
The unshift method adds one or more elements to the header of the array element, and moves the existing elements to the largest position of the subscript to free up space.
It returns the new length of the main family.
Shift is to delete and return the first element of the array, and then move all the following elements forward to fill the blank left by the first element.
*/
Var list = [];
List. unshift (6, 2 );
Document. write ("<br> the content of the list is:" + list );
Document. write ("<br> the shift method of list is:" + list. shift ());

// The rest is the toString () method we are familiar with in java.
// It's a piece of cake!
Document. write (c. toString ());
// To put it bluntly, the toString () method of the array has the same effect as the join () method without parameters.
// OK, this's chapter for Array, that's all!

</Script>

Related Article

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.