JS Array Operation Push,pop,shift,unshift and other methods detailed introduction

Source: Internet
Author: User
Tags javascript array

JS in the operation of the array of methods or more, today suddenly thought to summarize, but also known as warm so new bar. But not for each method, I just choose some of them.

first of all, the push and pop methods, these two methods will only be the array from the tail to press or eject, but also in the original arrays to operate, any changes will affect the operation of the array. Push (args) can press multiple elements at a time and return the updated array length. The pop () function only pops the last element at the end and returns the element that pops up and returns undefined if it is called pop () for the number of empty groups. If the argument is an array, the entire array is pressed into the original array as an element. does not produce a "split phenomenon" similar to concat merging arrays, see example below

Example 1:
var oldarr=[1,2,3];
alert (Oldarr.push (4,[5,6])) –>5 (this only evaluates [5,6] as an element, returning the updated array length 5)
at this time oldarr–>[1,2,3,4,[5,6]]
alert (Oldarr.pop ()) –>[5,6] (this pops up the last element [5,6] instead of 6)
at this time oldarr–>[1,2,3,4]
Oldarr.pop () –>4
Oldarr.pop () –>3
Oldarr.pop () –>2
Oldarr.pop () –>1
Oldarr.pop () –>undefined (empty array popup)
now finish the push and pop and take a look at Unshift and shift .
Both of These methods are performed on the head of the array, while others are similar to push and pop, but the Unshift method in IE returns the undefined

Example 2:
var oldarr2=[1,2];
Oldarr2.unshift (3) –>undefined
at this time OLDARR2 is –>[3,1,2]
oldarr2.shift () –>3
at this point oldArr2 is []
Next, take a look at the powerful splice, which can be used to add, delete, and manipulate elements at random positions in the original

Modify on array
Start in Splice (Start,deletecnt,args) indicates the beginning of the subscript, deletecnt indicates the number of elements to be removed from the start of the subscript, including the element, and the delete operation returns the deleted element. Args is used to replace deleted elements (which can have multiple arguments), and start and deletecnt must be numbers, and if not the number is attempted, the conversion fails as the zero processing. Splice must have at least one start element, otherwise no action will be made. DELETECNT does not exist to delete start and all subsequent elements (ie, take 0 do not delete). Start can be negative, indicating that the calculation begins at the right end of the array. deletecnt If a negative number is not deleted, it is not possible to delete negative elements.
All right, here's the explanation. Now take a look at the example, perhaps better understood by example

Example 3:
var oldarr3=[1,2];
Oldarr3.splice () –> "" (Returns an empty string, without any action, after Operation oldarr3–>[1,2])
Oldarr3.splice ("") –>[1,2] ("" Attempt to convert to a number failed to return 0, so delete 1, 2, after Operation Oldarr3–>[], but IE is a bit disgusting, do not do any action)
Oldarr3.splice ("1a") –> ibid .
Odlarr3.splice (0,2) –>[1,2] ("Start with the elements of subscript 0, delete two elements so delete oldarr3–>[])
Oldarr3.splice (0,-1) –> "" (starting from 0 subscript Delete-1 elements, so equal to no action, after Operation oldarr3–>[1,2])
Oldarr3.splice (–>2) (from subscript 1 to delete 1 elements, that is, delete 2, so after deletion oldarr3–>[1])
Oldarr3.splice (1,4) –>2 (delete 4 elements starting from subscript 1, 1 starts with only 1 elements, so delete 2, so delete oldarr3–>[1])
Oldarr3.splice ( -1,0,3) –> "" (remove 0 elements starting from subscript-1 i.e. 2 elements, then add element 3, so after Operation oldarr3–>[1,3,2])
Oldarr3.splice ( -1,1,3) –>2 (starting from 1, 2 elements to delete 1 elements and then adding element 3, after operation is oldarr3–>[1,3])
OK next start talking about Concat, which is used to concatenate two or more arrays, and the array does not change the original array but only returns a new array. When the parameter is concatenated, the element in the array is concatenated. Because the simpler and more straightforward start example

Example 4:
var oldarr4=[1,2];
oldarr4.concat (3,4) –>[1,2,3,4]
Oldarr4.concat (3,4,[5,6]) –>[1,2,3,4,5,6] (this side adds element 5 and element 6 in [5,6])
Oldarr4.concat (3,[4,[5,6]]) –>[1,2,3,4,[5,6] [the innermost element of this side [5,6] is used throughout to add, not disassemble)
the sorting method in the array is as follows sort
Sort (function) is the ordering of the original array, and no new arrays are generated. The default sort () is compared by converting the elements in the array to strings when they are not with parameters, and when the comparison is sorted by the order in which the characters are encoded in the character encoding, each character has a unique encoding corresponding to it.

and look at the following example
var oldarr5=[3,1,5,7,17] Look at this general idea that the OLDARR5 sort Oldarr5.sort () will return [1,3,5,7,17] According to the number from small to large, but look at the results actually return is [ 1,17,3,5,7] are converted to strings because of comparisons. Then the string is compared one by one if the first character is the same then the second, or directly return the comparison results, because "17″<" 3″ so it is conceivable that the result of sequencing is not the result of the general impression.

The sort (function) method in addition to the default non-parameter can also be passed to the custom sorting method, so that the results of the order can be controlled by themselves, how to arrange the row, is not very cool Ah, hehe. General Custom Function comparison functions that contain two parameters representing the left and right elements to compare. A result is then returned in a certain way, if the return value is greater than 0 to interchange the left and right elements, and if the return value is less than 0 or equal to 0, the left and right elements are not exchanged. Now take a look at the example

Example 5:
arrange the original array in numbers from large to small

Copy the Code code as follows:
var oldarr5=[3,1,5,7,17];//initial array
function Mysort (left,right) {
if (left<right) {
return 1;} Exchange two if the left element is less than the right element
else{
return-1;} If the left element is greater than or equal to the right element does not swap
}


Of course the above method can be simplified to funaction mysort (left,right) {return right-left;}

Copy the Code code as follows:
//According to an even number in the first odd number after sorting
var oldarr6=[3,6,7,18];//initial array
function MySort2 (left,right) {
if (left%2==0) return-1;//does not swap if the left element is an even number
if (right%2==0) return 1;//exchange if the right element is an even number
return 0;//No Exchange
}


The last slice not much, just to intercept some elements in the original array, return a new array, the original array will not change, and its operation is similar to the slice string

Copy the Code code as follows:


var oldarr7=[1,2,3,4];
Oldarr7.slice (0) –>[1,2,3,4]
Oldarr7.slice (0,2) –>[1,2]
Oldarr7.slice (0,0) –>[]
Oldarr7.slice (0,-1) –>[1,2,3]
Oldarr7.slice ( -3,-1) –>[2,3]
Oldarr4.slice ( -1,-3) –[]

1. Creation of arrays

Copy the Code code as follows:


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, the array is actually variable in all cases, meaning that even if the length is 5, the element can still be stored outside the specified length, note that the length changes accordingly.

2. Access to elements of an array

Copy the Code code as follows:


var testgetarrvalue=arrayobj[1];//Gets the element value of the array
arrayobj[1]= "This is the new value";//assigns a new value to the array element



3. Adding array elements

Copy the Code code as follows:


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, returning the new length of the array
Arrayobj.splice (insertpos,0,[item1[, item2[, ... [, Itemn]]]); /inserts one or more new elements into the specified position of the array, the element at the insertion position automatically moves back, and returns "".



4. Deletion of array elements

Copy the Code code as follows:


Arrayobj.pop ();//Remove the last element and return the element value
arrayobj.shift ();//Remove the first element and return the element value, the elements in the array are automatically moved forward
Arrayobj.splice (Deletepos,deletecount);//delete the element that is removed from the specified number of DeleteCount elements, starting at the specified position deletepos, in the array form



5. Interception and merging of arrays

Copy the Code code as follows:


Arrayobj.slice (Start, [end]);//Returns the part of the array as an array, noting that the end corresponding element is not included, and if the end is omitted, all elements after start are copied
Arrayobj.concat ([item1[, item2[, ... [, Itemn]]]); Concatenate multiple arrays (which can also be strings, or a mixture of arrays and strings) into an array, returning a new, well-connected array



6, copy of the array

Copy the Code code as follows:


arrayobj.slice (0);//Returns a copy array of the array, note that it is a new array, not a pointer to the
Arrayobj.concat ();//Returns a copy array of the array, note that it is a new array, not a pointer to the



7. Sorting of array elements

Copy the Code code as follows:


arrayobj.reverse ();//invert element (top row to last, last row to top), return array address
Arrayobj.sort ();//Sort an array of elements, return the arrays address



8. String of array elements

Copy the Code code as follows:


Arrayobj.join (separator);//Returns a string that connects each element value of an array together, separated by separator.
tolocalestring, toString, valueOf: Can be seen as a special use of joins, not commonly used



Ii. 3 properties of an array object

1. Length Property

The Length property represents the size of the array, which is the number of elements in it. Because the index of an array always starts with 0, the upper and lower bounds of an array are: 0 and length-1. Unlike most other languages, the length property of a JavaScript array is variable, which requires special attention. When the length property is set larger, the state of the entire array does not change in fact, only the length property becomes larger, and when the length property is set to an earlier hour, the value of the element whose index is greater than or equal to length in the original array is lost. Here is an example that shows changing the length property:

Copy the Code code as follows:


var arr=[12,23,5,3,25,98,76,54,56,76];
//Defines an array with 10 numbers
alert (arr.length);//Display the length of the array
arr.length=12;//Increase the length of the array
alert (arr.length);//The length of the display array has changed to
alert (arr[8]);//Displays the value of the 9th element as a
arr.length=5;//Reduce the length of the array to 5, and the elements with an index equal to or more than 5 are discarded
alert (arr[8]);//shows that the 9th element has changed to "undefined"
arr.length=10;//restore the array length to ten
alert (arr[8]);//Although the length is restored to 10, the 9th element cannot be retracted, showing "undefined"



By the above code we can clearly see the property of the length property. But the length object can be not only explicitly set, it may also be implicitly modified. You can use an undeclared variable in JavaScript, or you can use an undefined array element (an element that has an index that exceeds or equals length), at which point the value of the length property is set to the value of the index of the element being used plus 1. For example, the following code:

Copy the Code code as follows:


var arr=[12,23,5,3,25,98,76,54,56,76];
alert (arr.length);
arr[15]=34;
alert (arr.length);



The code also defines a 10-digit array, with the alert statement to see its length as 10. An element with an index of 15 is then assigned a value of 15, or arr[15]=34, and then the length of the array is output with the alert statement, resulting in 16. In any case, this is a surprising feature for developers who are accustomed to strongly typed programming. In fact, the initial length of an array created with the new Array () is 0, and it is the operation that does not define the element in it that changes the length of the array.

As you can see from the above introduction, the length property is so magical that it makes it easy to increase or decrease the capacity of the array. Therefore, an in-depth understanding of the length attribute can be used flexibly in the development process.

2. Prototype Properties

Returns a reference to the object type prototype. The prototype property is common to object.
Objectname.prototype
The ObjectName parameter is the name of the object.
Description: Provides a basic set of functions for a class of objects using the prototype property. The new instance of the object "inherits" the action given to the object's prototype.

For array objects, use the following example to illustrate the purpose of the prototype property.

Adds a method to the array object that returns the value of the largest element in the array. To do this, declare a function, add it to array.prototype, and use it.

Copy the Code code as follows:


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



After the code executes, Y saves the maximum value in the array x, or 6.

3. Constructor properties

Represents a function that creates an object.
Object.constructor//object is the name of the object or function.
Description: The constructor property is a member of all objects that have prototype. They include all JScript intrinsic objects except the Global and Math objects. The constructor property holds a reference to a function that constructs a particular object instance.

For example:

Copy the Code code as follows:


x = new String ("Hi");
if (x.constructor = = String)//Processing (condition is true).



Or

Copy the Code code as follows:


function MyFunc {
//function body.
}



Copy the Code code as follows:


y = new MyFunc;
if (y.constructor = = MyFunc)//Processing (condition is true).



For arrays:

Copy the Code code as follows:


y = new Array ();

JS Array Operation Push,pop,shift,unshift and other methods detailed introduction

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.