Open fxxqq opened 5 years ago
let arr = [2,4,434,43] let arr1= arr.slice() arr[0] = 'a' console.log(arr,arr1) // [ 2, 4, 434, 43 ] console.log(arr1 === arr) // false
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'] let arr2 = arr.clone() console.log(arr2) console.log( arr2 === arr )
Array.prototype.clone=function(){ return [].concat(this); //或者 return this.concat(); } let arr = ['aaa','asss'] let arr1 = arr.clone() arr[0] = 123 console.log(arr,arr1)
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 ]
const a1 = [1, 2]; const a2 = [...a1]; a1[0] = 'aaa' console.log(a1,a2)
ES5 方法总结
slice
遍历数组
concat()
ES6 方法总结
Object.assign() 浅复制,也可以实现数组的克隆
扩展运算符