JavaScript array operations (go heavy, sort, connect)

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

1, the creation of the array

The code is as follows Copy Code

var arrayobj = new Array (); Create an array

var arrayobj = new Array ([size]); Create an array and specify the length, note not the upper limit, is the length

var arrayobj = new Array ([element0[, element1[, ...) [, ELEMENTN]]]); Create an array and assign a value

To illustrate, although the second method creates an array that specifies the length, in all cases the array is longer, that is, even if you specify a length of 5, you can still store the elements outside the specified length, note: the length changes.

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

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

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

7, the ordering of array elements

The code is as follows Copy Code

Arrayobj.reverse (); Reverse element (top to last, last to top), return array address

Arrayobj.sort (); array element Sorting, returning the arrays address

8. String of array elements

The code is as follows Copy Code

Arrayobj.join (separator); Returns a string that connects each element value of an array, separated by a separator in the middle.

toLocaleString, toString, valueof: Can be seen as a special use of join, not commonly used

Example

The code is as follows Copy Code

<!doctype html>
<meta charset= "UTF-8"
<title > Array method </title>
<body>
<script type= "Text/javascript"
//concat () method is used to connect two or more arrays. The
//method does not change an existing array, but simply returns a copy of the connected array.
//arrayobject.concat (Arrayx,arrayx,......, arrayx)
//arrayx required. The parameter can be a specific value, or it can be an array object. Can be any number of.
var a = [1,2,3];
var B = a.concat (4,5);
var c = [' Jack ', ' Jonhn ', ' Tom '];
var d = [' Jim ', ' 111cn.net '];
var e = c.concat (d);
document.write (A + <br/>);//1,2,3
document.write (b + "<br/>");//1,2,3,4,5
document.write (E + "<br/>");

The join () method is used to put all elements in an array into a string. The elements are delimited by the specified delimiter.
Arrayobject.join (separator)
Separator optional. Specifies the separator character to use. If this argument is omitted, commas are used as delimiters.
var a1 = [1,2,3];
document.write ("Join Method <br/>" +a1.join () + "<br/>");
var B1 = [1,2,3];
document.write (B1.join (".") + "<br/>"); Use delimiters to separate elements in an array, outputting 1.2.3
document.write (The return value type of join () is: "+typeof (A1.join ()) +" <br/> ");

The Pop () method is used to delete and return the last element of the array.
Arrayobject.pop ()
Create an array, and then delete the last element of the array. Note that this also changes the extent of the array:
var a2 = [1,2,3];
var b2 = A2.pop ();
document.write (b2+ "<br/>"); Returns the last element of an array 3
document.write (a2+ "<br/>"); The original array has been changed to remove the last element and return to 1,2

The push () method adds one or more elements to the end of the array and returns a new length.
Arrayobject.push (Newelement1,newelement2,...., newelementx)
Newelement1 required. The first element to add to the array.
Newelementx Optional. Multiple elements can be added.
var a3 = [1,2,3];
var B3 = A3.push ("111cn.net");
document.write (b3+ "<br/>"); Output the new array length 4
document.write (a3+ "<br/>"); The original array has changed, 1,2,3,111cn.net

The reverse () method reverses the order of elements in an array.
Arrayobject.reverse () This method changes the original array without creating a new array.
var a4 = [1,2,3];
var b4 = a4.reverse ();
document.write (b4+ "<br/>"); Array Reverse 3,2,1
document.write (a4+ "<br/>"); Array has changed, and a4 = = B4;
document.write (a4 = = = B4); True

The shift () method deletes the first element of an array and returns the value of the first element.
Arrayobject.shift ()
The value of the original first element of the array.
If the array is empty, the shift () method does nothing, returning the undefined value. Note that the method does not create a new array, but instead directly modifies the original arrayobject.
var a5 = [1,2,3];
var B5 = a5.shift ();
document.write ("<br/>");
document.write (b5+ "<br/>"); Returns the first 1
document.write (a5+ "<br/>"); The array A5 has changed, returning to remove the first 2,3

The Unshift () method adds one or more elements to the beginning of the array and returns a new length. It's just the opposite of the order added to Pushu.
Arrayobject.unshift (Newelement1,newelement2,...., newelementx)
Newelement1 required. The first element added to the array. Newelementx Optional. You can add several elements.
IE 7 and below do not work correctly
var a6 = [' A ', ' B ', ' C '];
var b6 = a6.unshift (' d ');
document.write (b6+ "<br/>"); Returns the new length 4
document.write (a6+ "<br/>"); The original array has been changed, the output d,a,b,c

The slice () method returns the selected element from an existing array.
Arrayobject.slice (Start,end)
Start Required. Specify where to start the selection. If it is a negative number, then it sets the position from the end of the array. In other words,-1 refers to the last element, 2 to the penultimate element, and so on.
End is optional. Specify where to end the selection. The parameter is the array subscript at the end of the array fragment. If this argument is not specified, the Shard array contains all the elements from start to the end of the array. If this argument is a negative number, it sets the element that starts at the end of the array.
Returns a new array containing the elements in the arrayobject from start to end (excluding the element). Does not change the original array, but instead returns a child array
var a7 = [' A ', ' B ', ' C '];
var b7 = A7.slice (1,3);
document.write (b7+ "<br/>"); Returns the new array b,c
document.write (a7+ "<br/>"); The original array is unchanged A,B,C

The splice () method adds/deletes items to/from the array, and then returns the items that were deleted. This method changes the original array.
Arrayobject.splice (index,howmany,item1,....., itemx)
Index required. Integer that stipulates where to add/remove items, and use negative numbers to specify the position from the end of the array.
Howmany required. The number of items to delete. If set to 0, the item is not deleted.
Item1, ..., itemx Optional. The new item to add to the array.
var a8 = [' A ', ' B ', ' C ', ' d '];
var B8 = A8.splice (2,0, "Caibaojian")
document.write (a8+ "<br/>"); Output a,caibaoijan,b,c,d
alert (B8);
var C8 = A8.splice (1,3);
document.write (c8+ "<br/>");
document.write (A8);

The sort () method is used to sort the elements of an array.
Arrayobject.sort (SortBy)
SortBy Optional. Specify the sort order. Must be a function.
Returns a reference to the array of values. Note that the array is sorted on the original array and no replicas are generated.
var a9 = [' A ', ' f ', ' h ', ' C '];
var B9 = A9.sort ();
var C9 = [1,100,40,30,104,1000,4];
var D9 = C9.sort ();
document.write ("<br/>" +b9+ "<br/>"); A,c,f,h according to the letter output
document.write (a9+ "<br/>"); The original array has changed and the a,c,f,h is output in alphabetical order.
document.write (d9+ "<br/>"); 1,100,1000,104,30,4,40 numbers are not output by size and need to be customized in one order
function Sortnumber (a,b)
{
Return A-b
}
document.write (C9.sort (sortnumber) + "<br/>"); 1,4,30,40,100,104,1000

The Tosource () method represents the source code for the object.
The original value is inherited by all objects derived from the Array object.
The Tosource () method is usually invoked automatically in the background by JavaScript and does not appear explicitly in the code.
Only Gecko's core browsers, such as Firefox, support the approach, IE, Safari, Chrome, Opera, and so on are not supported by browsers.
Object.tosource ()

The ToString () method converts an array to a string and returns the result.
Arrayobject.tostring ()
Return value: A string representation of the Arrayobject. The return value is the same as the string returned by the join () method without parameters.
var A11 = [' A ', ' B ', ' C ', ' d '];
var B11 = a11.tostring ();
document.write (b11+ "<br/>");
document.write ("The return value type of ToString is:" +typeof (B11));

Arrayobject.tolocalestring ()

The valueof () method returns the original value of the Array object.
Arrayobject.valueof ()

</script>
<a href= "Http://111cn.net" > cloud-Habitat Community Network </a>
</body>

Results

1,2,3
1,2,3,4,5
Jack,jonhn,tom,jim,111cn.net
Join method
1,2,3
1.2.3
The return value type of join () is: string
3
1,2
4
1,2,3,111cn.net
3,2,1
3,2,1
True
1
2,3
4
D,a,b,c
B,c
A,b,c
A,b,caibaojian,c,d
A,d
A,c,f,h
A,c,f,h
1,100,1000,104,30,4,40
1,4,30,40,100,104,1000
A,b,c,d
The return value type of ToString is: string

Array to weight

1. Delete the following duplicates:

The code is as follows Copy Code
function Ov1 (arr) {
var a1= (new Date. GetTime ())
for (Var i=0;i<arr.length;i++)
for (Var j=i+1;j<arr.length;j++)
if (Arr[i]===arr[j]) {arr.splice (j,1); j--;}
Console.info (New Date). GetTime ()-a1)
Return Arr.sort (function (a,b) {return a-b});
}

2. This is the normal method, better understanding, if the same, jump out of the loop

The code is as follows Copy Code
function Ov2 (a) {
var a1= (new Date. GetTime ())
var b = [], n = a.length, I, J;
for (i = 0; i < n; i++) {
for (j = i + 1; J. < N; j + +)
if (a[i] = = A[j]) {J=false;break}
if (j) B.push (A[i]);
}
Console.info (New Date). GetTime ()-a1)
Return B.sort (function (a,b) {return a-b});
}

3. It took me a long time to understand where the J Loop went on, but the I value has changed. is equal to a new I loop:

The code is as follows Copy Code
function Ov3 (a) {
var a1= (new Date. GetTime ())
var b = [], n = a.length, I, J;
for (i = 0; i < n; i++) {
for (j = i + 1; J. < N; j + +)
if (a[i] = = A[j]) j=++i
B.push (A[i]);
Console.info (New Date). GetTime ()-a1)
Return B.sort (function (a,b) {return a-b});
}

4. Ensure that the new array is unique

The code is as follows Copy Code
function ov4 (AR) {
var a1= (new Date. GetTime ())
var m=[],f;
for (Var i=0;i<ar.length;i++) {
F=true;
for (Var j=0;j<m.length;j++)
if (Ar[i]===m[j]) {f=false;break;};
if (f) m.push (Ar[i])}
Console.info (New Date). GetTime ()-a1)
Return M.sort (function (a,b) {return a-b});
}

5. Use Object properties

The code is as follows Copy Code
function Ov5 (AR) {
var a1= (new Date). GetTime ()
var m,n=[],o= {};
for (var i=0; (m= ar[i])!==undefined;i++)
if (!o[m]) {N.push (m); o[m]=true;}
Console.info (New Date). GetTime ()-a1)
Return N.sort (function (a,b) {return a-b});;
}

The writing function is too powerful.

Results

The default array is: 1,2,3,4,2,3
The after-weight array is: 1,4,2,3
The sorted array is: 1,2,3,4
Use unique (): 2,3,4,34
Ov1 to Heavy: 1,2,4,10,22,23,24,40,42,44,100,1000,4444,dd,oooo,ooooo
Ov2 to Heavy: 1,OOOO,40,4,22,2,4444,OOOOO,100,44,1000,10,42,23,24,DD

Common method of Array object

Method Description
Concat () Connects two or more arrays and returns the result.
Join () Put all the elements of an array into a string. element is delimited by the specified delimiter.
Pop () Deletes and returns the last element of the array
Push () Adds one or more elements to the end of the array and returns a new length.
Reverse () Reverses the order of elements in an array.
Shift () Deletes and returns the first element of the array
Slice () Returns the selected element from an existing array
Sort () To sort the elements of an array
Splice () Deletes the element and adds a new element to the array.
Tosource () Returns the source code for this object.
ToString () Converts the array to a string and returns the result.
toLocaleString () Converts the array to a local array and returns the result.
Unshift () Adds one or more elements to the beginning of the array and returns a new length.
ValueOf () Returns the original value of an array object

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.