JS array use method and example tutorial

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

JS array use method and example tutorial
Defining arrays
An array object is used to store a series of values in a separate variable name.

We use the keyword new to create an array object. The following code defines an array object named MyArray:

The Var myarray=new array () has two methods of assigning values to an array (you can add as many values as you want, as you can define any number of variables you need).

1:
var mycars=new Array ()
mycars[0]= "Saab"
mycars[1]= "Volvo"
mycars[2]= "BMW" can also use an integer argument to control the size of the array:

var mycars=new Array (3)
mycars[0]= "Saab"
mycars[1]= "Volvo"
Mycars[2]= "BMW" 2:
var mycars=new array ("Saab", "Volvo", "BMW") Note: If you need to specify a numeric or logical value within an array, the variable type should be either a numeric variable or a Boolean variable, not a character variable.
accessing arrays
You can access a particular element by specifying the array name and the index number.

Here is the line of code:

document.write (Mycars[0]) below is the output:

Saab modifies the values in an existing array
If you want to modify the values in an existing array, add a new value to the specified bottom label:

Mycars[0]= "Opel"; now, the above code:

document.write (mycars[0]); output:

Opel

. How to create an array

2. How to operate the array (add, delete, read)

3. Array common methods and properties

How to create an array, generally based on the initialization of simple to divide into 3 kinds of:

1. Simply create an array:

var arr=new Array ();

Important: Create an Array object array () with the new keyword, and the array () object is a local class that you can use to create an object with new

2. Create an array and specify the size of the array:

var arr=new array (10);//This creates an array with an initialization size of 10.

Note: When you initialize the size by using an array size operation, the array is automatically propped up and does not make errors like the C language. Dynamic growth is a property of the JS array. In addition, JS supports the maximum array length of 4294967295

3. Direct initialization:

var arr=new array ("Paramecium", "Love", "fluffy");//This initializes the array directly.

or var arr=["Paramecium", "Love", "fluffy"];//parentheses can also declare an array object

Of course, like the C language, you can also define 2-D 3-dimensional arrays, which are not discussed here.

Properties of array: length

Arr.length returns the length of the array arr, which is common to the traversal of the arrays in the loop, such as:

for (Var i=0;i<arr.length;i++) {
Executive part
}

Array element access: Arr[index], in which index represents the array cardinality, from 0, a total of arr.length elements. For example: arr[0] access to the first array element, arr[1] access to the second array element .... How to do arrays by analogy: first overview of the following operations array of the common methods (13)

ToString (), valueof (), tolocalstring (), join (), split (), Slice (), concat (),
Pop (), push (), Shift (), unshift (), sort (), splice ()

The features and usage of these methods are analyzed below.

ToString (), valueof (), tolocalstring ():

Function: Returns all elements of an array

Note: Array names can also return the entire array

Code:

var m=["AM", "bm", "CM"];//declare an array object with parentheses

Alert (m.tostring ());//tostring () returns all the contents of the array object, separated by commas, that is am,bm,cm

Alert (m.valueof ());//valueof () also returns all contents of an array object

Alert (m.tolocalestring ());//tolocalestring () also returns all the contents of the array object, but there are regional language differences, no research

Alert (m);//array name also returns all contents of an array object

var m=["AM", "bm", "CM"];//declare an Array object alert (M.tostring ()) in parentheses,//tostring () returns all the contents of an array object, separated by commas, that is, AM,BM,CM alert ( ),//valueof () also returns all the contents of an Array object alert (m.tolocalestring ()),//tolocalestring () also returns all the contents of an array object, but there is a locale language difference, which does not temporarily study alert (m); Array names also return all the contents of an Array object
Run: <script>var m=["AM", "bm", "cm"];alert (m.tostring ()), Alert (m.valueof ()), Alert (m.tolocalestring ()); </ Script>

Join ():

Function: Connect an array of items with one character (string) without modifying the original array

Code:

var m=["AM", "bm", "CM"];//declare an array object with parentheses

var n=m.join ("---");//Connect am,bm,cm with---.

Alert (m.tostring ());//m has not been modified to return AM,BM,CM

alert (n);//n is a string, for AM---BM---cm

var m=["AM", "bm", "cm"];//with parentheses declare an array object var n=m.join ("---");///Connect am,bm,cm. Alert (m.tostring ()) with---;//m has not been modified to return to AM,BM, CM alert (n);//n is a string, for AM---BM---cm
Run: <script>var m=["AM", "bm", "cm"];var n=m.join ("---"); alert (m.tostring ()); alert (n);</script>

Split ():

Function: Splits a string into an array by a character (string), but does not modify the original string

Code:

var str= "I Love maomao,i am Caolvchong";

var arr=str.split ("O");//Divide the STR string into an array by character O

Alert (arr);//Output entire array

var str= "I Love maomao,i am Caolvchong"; var arr=str.split ("O");//split the STR string into an array alert (arr) by character O;/output the entire array
Running: <script>var str= "I Love maomao,i am Caolvchong"; var arr=str.split ("O"); alert (arr);</script>

Slice (): Returns an array portion of a position beginning (ending at a location) without modifying the original array

Code:

var m=["AM", "bm", "cm", "DM", "em", "FM"];

var n=m.slice (2);//Returns the element after the second element bm, that is, the CM,DM,EM,FM

var q=m.slice (2,5)//returns the second element after the fifth element, that is, Cm,dm,em

alert (n);

alert (q);

var m=["AM", "bm", "cm", "DM", "em", "FM"]; var n=m.slice (2);//Returns the element after the second element bm, that is, the CM,DM,EM,FM var q=m.slice (2,5);//Returns the second element after the fifth element, that is, Cm,dm,em alert (n); alert (q);
Running: <script>var m=["AM", "bm", "cm", "DM", "em", "FM"];var N=m.slice (2); var q=m.slice (2,5); alert (n); alert (q);< /script>

Stack operations for array objects:

Push (): Add an item at the end of the array

Pop (): Deletes the last item in an array

Code:

var m=["AM", "bm", "cm", "DM", "em", "FM"];

M.push ("GM")//add element at the end of the array GM

Alert (m);

M.pop ()//delete array last element GM

Alert (m);

var m=["AM", "bm", "cm", "DM", "em", "FM"]; M.push ("GM");//add element at the end of the array GM alert (m); M.pop ()//delete the last element of the array GM alert (m);
Run: <script>var m=["AM", "bm", "cm", "DM", "em", "FM"];m.push ("GM"), alert (m), M.pop (), alert (m);</script>

Queue operations for array objects:

Unshift (): Array header adds an item

Shift (): Deletes the first item in the array

Code:

var m=["AM", "bm", "cm", "DM", "em", "FM"];

M.unshift ("GM"); add element GM at the first element position of the array

Alert (m);

M.shift ()//delete the first element of the array gm

Alert (m);

var m=["AM", "bm", "cm", "DM", "em", "FM"]; M.unshift ("GM"); add element gm alert (m) at the first element position of the array; M.shift ()//delete the first element of the array, GM alert (m);
Run: <script>var m=["AM", "bm", "cm", "DM", "em", "FM"];m.unshift ("GM"); alert (m); M.shift (); alert (m); </script >

Sort (): Arrays are sorted by ASCII code of characters, modifying array objects

Note: Even the array of numbers will be converted to a string for comparison sort

Code:

var m=["AM", "FM", "GM", "BM", "em", "DM"];

M.sort ()//alphabetical order

Alert (m);

var m=["AM", "FM", "GM", "BM", "em", "DM"]; M.sort ()//alphabetical order alert (m);
Run: <script>var m=["AM", "FM", "GM", "BM", "em", "DM"];m.sort (); alert (m);</script>

Concat (): Adds an element to the end of an array without modifying the array object

Code:

var m=["AM", "BM"]

var n=m.concat ("cm");//Add a cm and give the new array object

Alert (m);//The original array has not been modified

alert (n);//output new Array object

var m=["AM", "bm"] var n=m.concat ("cm");//Add a cm and give new Array object alert (m);//original Array not modified alert (n);//output new Array object
Run: <script>var m=["AM", "BM"];var n=m.concat ("cm"); alert (m); alert (n);</script>

Splice (): Add, delete, or replace elements at any location in the array, directly modify the array object

Details:

Splice () has three parameters or more than three parameters, the first two are required, and the following parameters are optional

To add: Splice (starting item, 0, adding item)

Delete: Splice (start item, number of items to delete)

To replace: Splice (starting, replacing, replacing) this is actually a common result of adding deletes

Code:

var m=["AM", "BM"]

M.splice (1,0, "FM", "SM")//Add FM and SM after the first item, return to AM,FM,SM,BM

Alert (m);

M.splice (2,1)//Delete the item after the second item (that is, the third SM, return AM,FM,BM)

Alert (m);

M.splice (2,1, "mm");//Replace the item after the second item (that is, the third item, return AM,FM,MM)

Alert (m);

var m=["AM", "BM"] M.splice (1,0, "FM", "SM");//Add FM and SM after the first item, return to AM,FM,SM,BM alert (m); M.splice (2,1)//delete the following item (that is, the third SM, return AM,FM,BM) alert (m); M.splice (2,1, "mm");//Replace the following item (that is, the third item, return am,fm,mm) alert (m);
Run: <script>var m=["AM", "BM"];m.splice (1,0, "FM", "SM"), alert (m), M.splice (2,1), alert (m), M.splice (2,0, "mm"); Alert (m);</script>


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.


You can truncate an array by setting the length property of the array.
a.length=3;
if (a[3]==undefined)
{
document.write ("<br/> +a.length+" after A.length= "a[3]=");
}
Else
{
document.write ("<br/> +a.length+" after 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.