Summary of usage of push (), pop (), Unshift (), Shift () in JS

Source: Internet
Author: User

1, push (), pop () and Unshift (), Shift ()

These two groups operate as an array, and change the length and content of the arrays themselves.

The difference is that push (), pop () is added or subtracted from the end of the array, Unshift (), and Shift () are added or subtracted from the head of the array.

Vararr = [1, 2];

2. Push () and unshift ()

adds several elements to the tail/head of the array and returns the new length of the array;

Arr.push (3,4);//Returns the new length of arr 4

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

Arr.unshift (0,0.5); Returns the new length of arr 6

arr; arr = [0,0.5,1,2,3,4];

3, Pop () and Shift ()

Delete 1 elements from the end/head of the array (delete only 1)and return the deleted elements ; empty array is to continue to delete, not error, but return undefined;

Arr.pop (); Returns 4;

arr; arr = [0,0.5,1,2,3];

Arr.pop (); Returns 3;

arr; arr = [0,0.5,1,2];

Arr.shift ();//return 0;

arr; arr = [0.5,1,2]

  PS: pop () and shift () do not accept the parameter, even if the parameters are not egg use ~ ~;

Arr.pop (3); return 2; return to the last one forever;

arr; arr = [0.5,1];

Arr.shift (1); Returns 0.5; return to the first one forever;

arr; arr = [1];

Arr.pop (); returns 1;

arr; arr = [];

Arr.shift ()//return undefined;

arr; arr = [];

Summary of usage of push (), pop (), Unshift (), Shift () in JS

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.