JS Array How to push an object. JS Array operation Push,pop,shift,unshift JavaScript uses the Push method to add an element to the array end of the JavaScript array function unshift, shift, pop, push use

Source: Internet
Author: User
Tags array length javascript array

The push () function is used to add one or more elements to the current array and return the new array length. The new element will be added to the end of the array in turn.

This function belongs to the array object and is supported by all major browsers.

Grammar

Array.push (item1 [, items ...])
Parameters

Parameter description
Item1 any type to the element at the end of the current array.
Items optional parameter/any type other items to add to the end of the current array can have more than one.
Note: If the element type being added is an array type (array), it will still be treated as an element, except that the element is of type. If you want to merge two arrays, use the concat () function.
return value

The return value of the push () function is
Returns the length of the array after the element is added.

When you add a new element to an array, the length property of the array changes as well. Generally, the length property of an array is added N (n is the number of elements added).

Example & Description

Defining an Array Object
var array = ["Codeplayer", true];
Document.writeln (Array.Length); 2

Add an element to the array
var newlength = Array.push ("http://www.365mini.com");
Document.writeln (array); Codeplayer,true,http://www.365mini.com
Document.writeln (newlength); 3

Add multiple elements at once
Newlength = Array.push (2, 3, "Hello");
Document.writeln (array); Codeplayer,true,http://www.365mini.com,2,3,hello
Document.writeln (newlength); 6

The array will also be added as one of the elements
Newlength = Array.push (False, [15, 12]);
The "15,12" at the back of the output is the output of an element, except that the element is an array
Document.writeln (array); codeplayer,true,http://www.365mini.com,2,3,hello,false,15,12
Document.writeln (newlength); 8
Run code


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 to explain, I just choose some of them, interested friends can study

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

The start of the

Modify on Array
Splice (Start,deletecnt,args) indicates the start of the subscript, deletecnt represents 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.
Okay, 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, no action, 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 a bit disgusting, do not do any action)
Oldarr3.splice ("1a") –> ibid.
Odlarr3.splice (0,2) –>[1,2] ("Starting from the element of subscript 0, deleting two elements so that after deletion oldarr3–>[])
Oldarr3.splice (0,-1) –>" "(starting from 0 subscript Delete-1 elements, it is equal to no action, After Operation oldarr3–>[1,2])
Oldarr3.splice (–>2) (delete 1 elements from subscript 1, i.e. delete 2, so delete 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) –> "" ( Delete 0 elements from subscript-1 i.e. 2 elements, then add element 3, so after Operation oldarr3–>[1,3,2])
Oldarr3.splice ( -1,1,3) –>2 (start with 1 elements and 2 elements, and then add element 1, oldarr3–>[1,3])
OK next start concat, this method is used to concatenate two or more arrays, the array will not change the original array will only return a new array. When the parameter is concatenated, the element in the array is concatenated. Because it's simpler and more straightforward to start the 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:

Sort by an even number in the first odd number
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; Swap if the right element is an even number
return 0; Do not 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) –[]


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

JavaScript Array Object
Array Object
The Array object is used to store multiple values in a single variable.
To create the syntax for an Array object:
New Array ();
New Array (size);
New Array (Element0, Element1, ..., ELEMENTN);
Parameters
The parameter size is the expected number of array elements. Returns an array of length fields that will be set to the value of size.
Parameter element ..., ELEMENTN is a list of parameters. When you use these parameters to call the constructor array (), the elements of the newly created array are initialized to these values. Its length field is also set to the number of parameters.
return value
Returns the newly created and initialized array.
If you do not use parameters when calling the constructor array (), the returned array is empty and the length field is 0.
When the constructor is called, only one numeric argument is passed to it, and the constructor returns an array with the specified number and element undefined.
When an array () is called by another parameter, the constructor initializes the array with the value specified by the parameter.
When a constructor is called as a function, and the new operator is not used, its behavior is exactly the same as when it is called with the new operator.
Array Object Properties
Property Description
Constructor returns a reference to the array function that created this object.
Length Sets or returns the number of elements in the array.
Prototype gives you the ability to add properties and methods to objects.
Array Object method
Method description
Concat () joins two or more arrays and returns the result.
Join () Places all 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 the new length.
Reverse () Reverses the order of the elements in the array.
Shift () deletes and returns the first element of the array
Slice () returns the selected element from an existing array
Sort () Sorts the elements of an array
Splice () Deletes the element and adds a new element to the array.
Tosource () returns the source code of the 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 the new length.
ValueOf () returns the original value of the array object

How much


JavaScript array functions unshift, shift, pop, push usages

Submission: Junjie font: [Increase decrease] Type: Reprint time: 2014-08-27 I want to comment
This article mainly introduces the JavaScript array function unshift, shift, pop, push use instance, this article first explained the method of declaring an array, and then the use of 4 functions give some examples, the need for friends can refer to the following
How to declare an array
Declarations of arrays in s can be declared in several ways
Copy the code code as follows:

var tmp = []; Shorthand mode
var tmp = new Array (); Direct New One
var tmp = Array (); Or new can also

In the new array, you can pass in a parameter that represents the initialization length of the array.
Copy the code code as follows:

When new, a parameter is passed to indicate the initialization of the array length
var tmp = new Array (3);

alert (tmp.length); 3

But if you want to create an array with only one element 3, then using the new method is not possible, because the system will treat your incoming 3 as the length of the array, unless you use quotation marks as strings, such as
Copy the code code as follows:

var tmp = new Array (' 3 ');
Alert (TMP); 3

We can create arrays using shorthand mode so that we can create an array with only one number element 3
Copy the code code as follows:

var tmp = [3]
Alert (typeof tmp[0]); Number

You can also initialize multiple elements, and the value of an element can be any type
Copy the code code as follows:

Simple mode to create an array
The elements of an array can be any data type
var tmp = [3,true,8.5,{' name ': ' Lizhong '},[' a ', ' B '];
alert (tmp.length); 5
Unshift inserting an element before the first element of the array
Copy the code code as follows:

Inserting an element before the first element of the array using Unshift
Returns the array length
var tmp = [' A ', ' B '];
var len = tmp.unshift (' C ');
alert (len); 3
Alert (TMP); C,a,b

You can also insert more than one element at a time, sequentially from the left
Copy the code code as follows:

Inserting an element before the first element of the array using Unshift
Returns the array length
var tmp = [' A ', ' B '];
var len = tmp.unshift (' C ', ' d ');
alert (len); 4
Alert (TMP); C,d,a,b
Second, shift pops the first element of the array and returns the value of the element being popped.
Small instance:
Copy the code code as follows:

Use shift to pop up the first element of an array
Returns the value of the element being ejected
var tmp = [' A ', ' B ', ' C '];
var val = Tmp.shift ();
Alert (val); A
Alert (TMP); B,c

If it is an empty array:
Copy the code code as follows:

Use shift to pop up the first element of an array
Returns the value of the element being ejected
var tmp = [];
var val = Tmp.shift ();
Alert (val); Undefined
Alert (TMP); Empty
Push to add an element at the end of the array
As opposed to unshift, push adds an element at the end of the array, returning the array length after adding the element
Copy the code code as follows:

To add multiple elements to the end of an array using push
Returns the latest array length
var tmp = [' A ', ' B ', ' C '];
var len = Tmp.push (' d ');
alert (len); 4
Alert (TMP); A,b,c,d

You can also add more than one element at a time
Copy the code code as follows:

To add multiple elements to the end of an array using push
Returns the latest array length
var tmp = [' A ', ' B ', ' C '];
var len = Tmp.push (' d ', ' e ', ' f ');
alert (len); 6
Alert (TMP); A,b,c,d,e,f
The pop function deletes the element at the end of the array
Instead of shift, pop pops up the element at the end of the array, returning the value of the element being popped.
Copy the code code as follows:

Pop-up array end elements using pop
Returns the value of the element being ejected
var tmp = [' A ', ' B ', ' C '];
var val = Tmp.pop ();
Alert (val); C
Alert (TMP); A, b

Returns undefined if the array is empty
Copy the code code as follows:

Pop-up array end elements using pop
Returns the value of the element being ejected
var tmp = [];
var val = Tmp.pop ();
Alert (val); Undefined
Alert (TMP); Empty


Using the above four functions, we can do some queue processing, the specific case will not write code.
The push function can actually be implemented as well.
Copy the code code as follows:

var tmp = [' A ', ' B ', ' C '];
Tmp[tmp.length] = ' d ';
Alert (TMP); A,b,c,d

Note: The above four functions unshift, shift, pop, and push functions will be modified on the array itself.

JS Array How to push an object. JS Array operation Push,pop,shift,unshift JavaScript uses the Push method to add an element to the array end of the JavaScript array function unshift, shift, pop, push use

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.