JS array operation (add, delete, change, check)

Source: Internet
Author: User

The array is a very common object in JS, it has some classic operation, today's zero for everyone introduction.

First, there are two ways to declare an array:

var arr = []; or varnew Array ();

The general use of the first, in the creation of the time can be placed directly inside the data, you can also add later.

First, add data to the array

There are two ways to use it:

1.push method to add data to the end of the array

Arr.push (' A ', ' B '); alert (arr);     // A, b

2.unshift method to add data to the beginning of the array

Arr.unshift (' 1 '); alert (arr);      // 1,a,b

Second, delete array data

There are two ways to use it:

1.pop method to delete a data at the end of an array

Arr.pop (); alert (arr);      // 1,a

2.shift method to delete a data at the beginning of an array

Arr.shift (); alert (arr);      // a

Third, change the array data

Here's a powerful way to use the array splice

Arr.splice (0,1, ' a ', ' B ', ' C '); alert (arr);        // A,b,c

The first parameter of the splice method is where you want to delete or add the element, the second parameter is the number of elements to delete, and the third and subsequent arguments are the elements to be added.

Iv. query Extraction of arrays

The method used is the slice method

var arr1 = Arr.slice (0,2); alert (arr1);      // A, balert (arr);      // A,b,c

The first parameter of the slice method is to extract the beginning subscript of an element, and the second parameter is to extract the end subscript of the element, noting that the slice method simply extracts the data and does not change the value of the original array.

JS array operation (add, delete, change, check)

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.