1. 程式人生 > >克隆陣列的幾種方式?

克隆陣列的幾種方式?

大致總結了五種方法,一起看看吧~~·

(一)slice方法

let arr = [1,2,3,4]
let arr1= arr.slice()  //或者是   let arr1= arr.slice(0)
arr[0] = 6
console.log(arr)   // [6, 2, 3, 4]
console.log(arr1)  // [1, 2, 3, 4]

(二)自己封裝一個myClone函式

Array.prototype.myClone = function(){
    let newArr=[];
    for(let i=0;i<this.length;i++) {
        newArr.push(this[i]);
    }
    return newArr;
}
let arr = ['aaa','bbb','ccc','wwwww','ddd']
let arr2 = arr.myClone()
console.log(arr)   //["aaa", "bbb", "ccc", "wwwww", "ddd"]
console.log(arr2)  //["aaa", "bbb", "ccc", "wwwww", "ddd"]
console.log( arr2 === arr )   //false

(三)展開運算子 [...arr]  

const arr1 = [1, 2];
const arr2 = [...a1];
arr1[0] = 6
console.log(arr1) // [6, 2]
console.log(arr2) // [1, 2]

(四)concat方法

var  arr1 = [1,2,3]
var  arr2 = arr1.concat()   //或者是  var  arr2 = arr1.concat([])
arr1[0] = 6
console.log(arr1)  //[6,1,2]
console.log(arr2)  //[1,2,3]

(五)Object.assign()

let arr = [1,2,3,4]
let arr1 = []
Object.assign(arr1,arr)
arr[0] = 6
console.log(arr)  // [6, 2, 3, 4] 
console.log(arr1) // [1, 2, 3, 4]   

嘻嘻嘻嘻嘻~~~