JS Array Common methods, the copy of the array (does not affect the original array), the array of equal __JS

Source: Internet
Author: User
Tags array length
Ways to change the original array:POPs (); Deletes the first element of the tail and returns the element;
var a = [1,2,3];
var B = A.pop ();
Console.log (a);//[1,2]
Console.log (b);//3
Similar methods:
push (); tail pushing; returning array length;
Shift (); top eject; return the element;
Unshift (), top sub-entry, return array length, reverse (), reverse array, return inverted array, splice (); Common method; Returns the array of deleted numbers, which can be []; methods that do not change the original array:Concat: Returns the concatenation of the array, does not change the original array; forEach; Map; join (); Returns the concatenation of the string, you can specify the interval;
Attention:
[1,2,3].join (')
//"123"
[1,2,3].join ()
//"1,2,3"
Slice (start,end); intercept the array, return the intercepted part, do not change the original array; sort (); Pass a function as an argument, which can be controlled in ascending order, descending or random; (try to produce random numbers); toString (); [1,2,3].tostring () ==[1,2,3].join (); Array Copy

An array is a reference type; simple assignment simply adds a pointer to an array; ex:

var a = [1,2,3];
var b = A;
B.push (2);
Console.log (a)//[1,2,3,2]

So how to achieve a separate copy. Introduce the following two methods: The performance of the two methods is not significant, different browser kernels have advantages and differences:

Method 1
var a = [1,2,3];
var B = A.slice ();
A.reverse;
Console.log (a);//[3,2,1]
Console.log (b);//[1,2,3]
//Method 2
var c = [4,5,6];
var d = c.concat ();
C.reverse ();
Console.log (c);//[6,5,4]
Console.log (d);//[4,5,6]
Array Equality

Let's talk about the pit first:
Any two array equality returns FALSE;[]=[];//FALSE
What to do. Do not compare each item to see the method available above: toString ();
The conversion to a string is more than once.

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.