ES5 方法总结
1.slice
let arr = [2,4,434,43];
let arr1= arr.slice();
//let arr1 = arr.slice(0);
arr[0] = 'a';
console.log(arr,arr1); // [a,4,434,43] [ 2, 4, 434, 43 ]
2. 遍历数组
Array.prototype.clone = function(){
let a=[];
for(let i=0,l=this.length;i<l;i++) {
a.push(this[i]);
}
return a;
}
let arr = ['aaa','bbb','ccc','wwwww','ddd'];
arr[0] = 'a';
let arr2 = arr.clone();
console.log(arr,arr2);//['a','bbb','ccc','wwwww','ddd'] ['aaa','bbb','ccc','wwwww','ddd']
3. concat()
Array.prototype.clone=function(){
return [].concat(this);
//或者 return this.concat();
//或者 return this.concat([]);
}
let arr = ['aaa','asss']
let arr1 = arr.clone()
arr[0] = 123
console.log(arr,arr1)//[123,'asss'] ['aaa','asss']
ES6 方法总结
1. Object.assign() 浅复制,也可以实现数组的克隆
let arr = ['sdsd',123,123,123]
let arr1 = []
Object.assign(arr1,arr)
arr[1] = 'aaaa'
console.log(arr,arr1) // [ 'sdsd', 'aaaa', 123, 123 ] [ 'sdsd', 123, 123, 123 ]
2. 扩展运算符
const a1 = [1, 2];
const a2 = [...a1];
a1[0] = 'aaa'
console.log(a1,a2)// ['aaa',2] [1,2]