This article brings you an introduction to the method of array cloning in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
js is mainly divided into two categories: Basic data types and Reference data types
Basic data types include: number, string, undefine, null, boolean, Symbol (new in es6)
Reference data types: Object, Array, Function, Data, etc.
Note: Basic data types are placed in the stack space and are stored by value and can be read directly Fetch and operation.
The reference data type is stored in the **heap space** (door). The value of the variable actually points to the address (key) of the heap space. Therefore, if you clone this variable, it is equivalent to copying the key.
let arr = [1,2,3,4,5] let arr1 = arr // 这一步相当于把arr栈空间的地址赋给了arr1,其实arr和arr1操作的是同一个堆空间的对象 arr1.push(6) // arr1 = [1,2,3,4,5,6] console.log(arr) //[1,2,3,4,5,6]
So for reference type copy, you need to copy the object in the heap space
Array shallow copy
1. Use array slice and The concat method returns a Characteristics of a new array
let arr = [1,2,3,4,5] let arr1 = arr.slice() //[1,2,3,4,5] let arr2 = arr.concat() //[1,2,3,4,5]
2. Simple and crude method - traversal
let arr = [1,2,3,4,5] let arr2 = [] arr.forEach(item=>{ arr2.push(item) } ) console.log(arr2)
3.es6 new method-expansion operator
let arr = [1,2,3,4,5] let arr1 = [...arr] //[1,2,3,4,5]
4.es6 new method-Object.assign
let arr = [1,2,3,4,5]
let arr1 = []
Object.assign(arr1,arr)
console.log(arr1) //[1,2,3.4,5]
If arrays and objects are nested in the array, shallow copy will only copy the array or object and store it in the stack space The address , so no matter whether the object pointed to by this address is changed in the old or new array, both arrays will change. Therefore we need deep copy to copy such array.
Array deep copy
1. Ordinary traversal, copy the reference type when traversing to the reference type
let arr = [1,2,3,4,5,{name:'bob'},['a','b']] function clone (arr) { let arr1 = [] arr.forEach(item=>{ //如果不是object,将该值插入到新数组 if(typeof(item) !== 'object') { arr1.push(item) } else { //根据遍历的对象新建一个相同类型的空对象 let obj = item instanceof Array ? [] : {} for(var key in item){ if(item.hasOwnProperty(key)){ obj[key] = item[key] } } arr1.push(obj) } }) return arr1 } let arr1 = clone(arr) arr1[5].name = 'js' console.log(arr,'arr',arr1,'arr1')
2. Simple and crude (can copy arrays and objects , but the function cannot be copied)
let arr = [1,2,3,4,5,{name:'bob'},['a','b']] let arr1 = JSON.parse(JSON.stringify(arr))
This article has ended here. For more other exciting content, you can pay attention to the JavaScript Tutorial Video column of the PHP Chinese website!
The above is the detailed content of Introduction to the method of array cloning in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!