Summary of application of arrays in JavaScript

Source: Internet
Author: User

recently, in summarizing the relevant application of JavaScript, the array part of JS is summarized today, in order to have some reference in the future work.

1. There are two ways to define arrays in JS:

var a = [1,2,3,4];

var B = new Array (1,2,3,4);

There is no difference between the two ways to create an array, which you can choose to use according to your own habits.

2. Modify the length of the array by command:

For example:var a = [1,2,3,4,5];

alert (a);

   

When executed:a.length = 3;

alert (a);

    

When we define the length of the array, the arrays are truncated according to the length of the set, and can be used to empty the array dynamically (A.LENGTH=0)

3. Addition and deletion of array elements

var arr = [1,2,3,4];

Push: Adds an element Arr.push (5) to the tail of the array; ' 1,2,3,4,5 '

Pop: The trailing element is deleted arr.pop (); ' A '

Unshift: add element Arr.unshift (5) to the head of the array; ' 5,1,2,3,4 '

Shift: Delete the head element arr.shift (0); ' 2,3,4 '

Splice: Delete at the specified location:

Splice (starting, length) Arr.splice (2,2); ' All '

Splice (starting, length, element to replace) Arr.splice (2,2,1,2,3) ' 1,2,1,2,3 '

Concat: Connect two arrays var a=[0.1,0.2]; var C = Arr.concat (a) ' 1,2,3,4,0.1,0.2 '

Join: Concatenate the array with a custom delimiter into a string Arr.join ("# #");

Sort: Sorts the array arr.sort (); This sort is sorted by character, unable to sort numbers, can be improved by adding custom functions

Arr.sort (function (n1,n2) {

return n1-n2;

})

Judged by the sign of the return value, regardless of the return number size

Summary of application of arrays in JavaScript

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.