Instructions for using JavaScript arrays

Source: Internet
Author: User
Tags array length arrays javascript array

The definition of JS array:

The code is as follows Copy Code

Method 1.

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

Method 2.

Define and initialize together:

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

Or another way of writing:

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


2, access to elements of the array

The code is as follows Copy Code

var testgetarrvalue=arrayobj[1]; Gets the element value of an array

Arrayobj[1]= "This is the new value"; Give a new value to an array element

3, the addition of array elements

The code is as follows Copy Code

Arrayobj. Push ([Item1 [item2 [...] [Itemn]]]); /Adds one or more new elements to the end of the array and returns the new length of the array

Arrayobj.unshift ([Item1 [item2 [...] [Itemn]]]); /Adds one or more new elements to the beginning of the array, the elements in the array are automatically moved back, and the new length of the array is returned

Arrayobj.splice (insertpos,0,[item1[, item2[, ...) [, Itemn]]]); /inserts one or more new elements into the array at the specified position, and the element at the insertion point is automatically moved back to "".

4, the deletion of the elements of the array

The code is as follows Copy Code

Arrayobj.pop (); Removes the last element and returns the element value

Arrayobj.shift (); Removes the first element and returns the element value, and the elements in the array are automatically moved forward

Arrayobj.splice (Deletepos,deletecount);


Deletes the specified number of DeleteCount elements starting at the specified position, deletepos the removed elements

5, the array of interception and merging

The code is as follows Copy Code

Arrayobj.slice (start, [end]);

Returns a portion of an array as an array, noting that the end-corresponding element is not included, and if omitting the end copies all elements after start

Arrayobj.concat ([item1[, item2[, ...) [, Itemn]]]);

Concatenate multiple arrays (or a string, or a mixture of arrays and strings) into an array, returning a new array of connections


6, the copy of the array

The code is as follows Copy Code

Arrayobj.slice (0); Returns an array of copies, noting that a new array is not a pointer to the

Arrayobj.concat (); Returns an array of copies, noting that a new array is not a pointer to the

JavaScript two-dimensional array:

JavaScript uses one-dimensional arrays to simulate two-dimensional arrays:

Method 1.

var arr = new Array ([' A ', ' B ', ' C '],[' d ', ' e ', ' f ']);
ARR[0] Returns the first one-dimensional array, 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 ()
);

Data Lookup Maximum 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:

The JavaScript array does not need to be set in length, it expands itself, and the array name. Length returns the number of elements

Code

The code is as follows Copy Code

var arr=[12,23,5,3,25,98,76,54,56,76];

Defines an array that contains 10 digits

alert (arr.length); Displays the length of the array 10

arr.length=12; Increase the length of an array

alert (arr.length); The length of the display array has changed to 12

Alert (arr[8]); Displays the value of the 9th element, which is 56

arr.length=5; Reduces the length of the array to 5, and the elements indexed equal to or more than 5 are discarded

Alert (arr[8]); Show 9th element has changed to "undefined"

arr.length=10; Restores the array length to 10

Alert (arr[8]); Although the length is restored to 10, the 9th element cannot be retracted, displaying "undefined"

Common functions:

Common functions for arrays

ToString (): Converts an array to a string
toLocaleString (): Converts an array to a string
Join (): Converts an array into a symbolic concatenated string
Shift (): Moves an element of an array's head out
Unshift (): Inserts an element in the header of an array
Pop (): Deletes an element from the tail of an array
Push (): Adds an element to the tail of the array
Concat (): Adding elements to an array
Slice (): Returns the part of an array
Reverse (): Sort the array in reverse order
Sort (): Sorting operations on array
Splice (): Inserts, deletes, or replaces an array element

JavaScript Array Ordering:

Arrayobj.sort (sortfunction)

Parameters

Arrayobj
Array
Sortfunction
Options available. comparison function. If this argument is omitted, then the elements are sorted in ascending order in ASCII characters.
The comparison function must return one of the following values:

* Negative value if the first argument passed is smaller than the second argument.
* Zero if two parameters are equal.
* Positive value if the first argument is larger than the second argument

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

Summary of array usage methods

The code is as follows Copy Code


<script language= "JavaScript" >

/*
Because JavaScript is an untyped language, elements of an array can have arbitrary data types, and different elements of the same array
can have different types, the element settings of an array can contain other arrays, so you can create a complex array.
And at this point JavaScript is different from the rigorous object-oriented C++.c#,java as a scripting language. With greater flexibility.
*/

/*
* in javascript1.1 and subsequent versions, the array is created with the constructor array () and operator new.
You can create an array in JavaScript in the following three ways.
*/
var a=new Array ();
var b=new Array (5,4,3, "a", "test,string");
var c=new Array (20);

a[1.23]= "Test";
document.write ("a[1.23]=" +a[1.23]);
Believe that every time you learn JavaScript from a strongly typed programming language, you'll definitely be surprised by this action,
Float data is also count the group, in fact not what you think
JavaScript will convert it to a string when you are using negative numbers, floating-point numbers, (or Boolean, objects, other values)
Using the generated string as the property name of the object, rather than defining a new array element
The example above is the fact that a property named: "1.23" was created for a.
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 tests also make it clear that we use integers as subscripts for arrays to actually add an element to the array.
This uses the length of the array to reflect the subtleties of the JavaScript array.

The


 //can truncate the length of an array by setting an array's Length property.
 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]=") ;
 }

 //here to test our multidimensional array elements
 /*
 *javascript does not actually support multidimensional arrays
 * But we assign elements of one one-dimensional array to one one-dimensional array, This looks like a multidimensional array, but
  is actually a one-dimensional array, which is the same idea we have when we understand an array of C, but their implementation mechanism is different.
 */
 var g=new Array (3);
 g[3]=a;
 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;
 docum Ent.write ("<br/>c[i]=" +c[i));
 } The
  document.write ("<br/>c element Join () method is followed by:" +c.join ());
 //Array reverse () method
  C.reverse ();
  document.write ("<br/>c element joins in the reverse () method () The result is: "+c.join (" | "));

Testing of the concat () method
var h=new Array (1,2,3);
H= H.concat ([4,5]);
However, the concat function does not recursively expand an array of elements.
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 argument and the element that starts at the second parameter specified by the
Element but does not contain the element specified by the second argument.


Splice () method
The splice () method is a common method for inserting or deleting an array element.
/*
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 removed from the array
After the second parameter, you can have as many parameters as you want, and they specify the elements that are inserted from the position specified by the first parameter.
The first element and subsequent elements, make the corresponding move.
*/

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


Arrays in JavaScript are similar to PHP when used as stacks
This is interesting and more useful.
The following is a small instance used as a stack
/*
The push method is to attach one or more new elements to the end of the array, and then return the new length of the array.
The pop deletes the last element of the array, sticks to the length of the array, and returns the value he deleted.
*/
var stack=new Array ();
Stack.push (1,2);
document.write ("<br>stack element is:" +stack);
document.write ("<br/>stack.length=" +stack.length);
The result of the document.write ("<br>stack.pop () return 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 head of an array element, and then moves the existing element to the largest position in the subscript and has room
, it returns the new length of the host family.
Method Shift is to delete and return the first element of the array, and then move all subsequent elements forward to fill the space left by the first element.
*/
var list=[];
List.unshift (6,2);
document.write ("<br >list content is:" +list);
The document.write ("<br>list shift method is:" +list.shift ());

In addition, the ToString () method that we are familiar with in Java is left
It ' s a piece of cake!
document.write (C.tostring ());
In fact, the effect of the array's ToString () method and the no-parameter join () is exactly the same
Ok,this ' s chapter for Array,that ' s all!

</script>

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.