数组 复制 拷贝 相等判断

js 数组的拷贝(不影响原数组),数组相等判断

数组拷贝

数组属于引用类型;简单的赋值只是添加了一个指向数组的指针;ex:

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

对新数组 b 的操作同样会改变原始数组 a

那么如何实现独立的拷贝?介绍下面两种方法:两种方法性能上相差不大,不同浏览器内核上各有千秋:

//方法1
var a = [1,2,3];
var b = a.slice();
a.reverse;
console.log(a);//[3,2,1]
console.log(b);//[1,2,3]
//方法2
var c = [4,5,6];
var d = c.concat();
c.reverse();
console.log(c);//[6,5,4]
console.log(d);//[4,5,6]

//数值复制拷贝例子  多维数组
//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);//不改变原始数组
//console.dir(d); //不改变原始数组
//console.dir(fruits);

 ----------------------------------------------------------------------

改变原数组的方法:

  1. pop();删除尾部的第一个元素并且返回这个元素;
var a = [1,2,3];
var b = a.pop();
console.log(a);//[1,2]
console.log(b);//3
  1. 类似方法: 
    push();尾部推入;返回数组长度; 
    shift();顶部弹出;返回该元素; 
    unshift();顶部亚入;返回数组长度;
  2. reverse();反转数组;返回反转后的数组;
  3. splice();常用方法;返回被删除的数组成的数组,可以为[];
  4. sort();排序;传入一个函数作为参数,可以控制为升序,降序或者随机;(try用来产生随机数);

不改变原数组的方法:

  1. concat:返回拼接后的数组,不改变原数组;
  2. forEach;
  3. map;
  4. join();返回拼接后的字符串,可以指定间隔;
//attention:
[1,2,3].join('')
//"123"
[1,2,3].join()
//"1,2,3"
  1. slice(start,end);截取数组,返回截取的部分,不改变原始数组;
  2. toString();[1,2,3].toString()==[1,2,3].join();

数组相等判断

先说下坑吧: 
任意两个数组相等都会返回false;[]=[];//false 
怎么办?千万不要逐项去比较,看看上面可用的方法:toString(); 
转化为字符串一次就比较完了。

方法一:适用 单层 数组嵌套的深拷贝
var ary2 = ary1.concat();
 
方法二:适用 多层 数组嵌套的深拷贝
var ary2 = JSON.parse(JSON.stringify(ary1));
  //此方法适用于Oject的深度拷贝,因为Array属于Oject类型,所以也适用于此处;
  //需要注意的是:作为Oject的深度拷贝时,要复制的function会直接消失,所以这个方法只能用在单纯只有数据的对象。
 
 
https://www.cnblogs.com/juneling/p/9149969.html

转载来源:http://blog.csdn.net/lance_10030/article/details/75258204?locationNum=1&fps=1

js array 相关资料  http://www.runoob.com/jsref/jsref-obj-array.html

-------------下面才是重点---------------------------------

数组深拷贝汇总:

https://www.cnblogs.com/hao-1234-1234/p/11801333.html

原文地址:https://www.cnblogs.com/hao-1234-1234/p/8525508.html