Copy of JS Array (does not affect the original array), array equivalence judgment array copy
An array is a reference type; A 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]
对新数组 b 的操作同样会改变原始数组 a
So how do you implement a separate copy? The following two methods are introduced: the performance of the two methods is not small, different browser cores are unique:
//method 1var a = [1,2,3];var B = a.slice (); A.reverse;console.log (a); //[1,2,3]//method 2var c = [4,5,6]; var d = c.concat () c.reverse (); Console.log (c); //[6,5,4]console.log (d); //[4,5,6]
//Numeric Copy copy example multidimensional array
//var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango", ["Banana", "Orange", "Lemon", "Apple", "Mango"];
//var mybest = fruits.slice (0);
//mybest.push ("Hello");
//mybest.push ({name: "Hao", age:12});
//var d = mybest.concat ();
//d.reverse ();
//console.dir (mybest),//Do not change the original array
//console.dir (d);//Do not change the original array
//console.dir (fruits);
----------------------------------------------------------------------
Ways to change the original array:
- Pop (); Deletes the first element of the trailer 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 (); trailing; returns the array length;
Shift (); top popup; return the element;
Unshift (); The top sub-entry; Returns the length of the array;
- Reverse (); reverses the array; returns the inverted array;
- Splice (); a common method; Returns an array of the number of deleted elements, 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); intercepts an array, returning the intercepted part without altering the original array;
- Sort (); To pass in a function as a parameter, which can be controlled as ascending, descending or random; (try is used to generate random numbers);
- ToString (); [1,2,3].tostring () ==[1,2,3].join ();
Array equality judgment
First, the Pit bar:
Any two arrays that are equal will return a False;[]=[];//false
What to do? Do not compare to each other, look at the methods available above: toString ();
The conversion to a string is done at once.
Reprint Source: Http://blog.csdn.net/lance_10030/article/details/75258204?locationNum=1&fps=1
Array Copy copy equality judgment