Copying an array is to store each item of the original array in a new array. In this way, the other array will not be affected while operating on the array. Because the array is a reference value, the variable value cannot be directly copied while copying the array.
cycle
Var ary1 = [1, 2, 3]; for (var i = 0, ary2 = Array(ary1.length); i < ary1.length; i++) ary2[i] = ary1[i];Copy the code
slice
Var ary1 = [1, 2, 3]; var ary2 = ary1.slice();Copy the code
The operator
Var ary1 = [1, 2, 3]; var ary2 = [...ary1];Copy the code
from
Var ary1 = [1, 2, 3]; var ary2 = Array.from(ary1);Copy the code
concat
Var ary1 = [1, 2, 3]; var ary2 = [].concat(ary1);Copy the code
When it comes to deep copy, arrays and objects are special, so when writing methods to do different processing, the code is as follows:
Let ary = [1,[2, {name: "zhang3 "}]]; function copyAry(options) { return copy(options) } function copy(ary) { let newAry = [] for (const item of ary) { let value = item; if (Object.prototype.toString.call(value) === "[object Object]") value = copyObj(value); if (Object.prototype.toString.call(value) === "[object Array]") value = copyAry(value); newAry.push(value); } return newAry; } function copyObj(obj) { let newObj = {}; for (const key in obj) { let value = obj[key]; if (Object.prototype.toString.call(value) === "[object Object]") value = copyObj(value); if (Object.prototype.toString.call(value) === "[object Array]") value = copyAry(value); newObj[key] = value; } return newObj; } // test let newAry = copyAry(ary); Ary [1] [1]. Name = "bill" is the console. The log (newAry [1] [1]. The name). / / zhang SAN console log (ary [1] [1]. The name) / / billCopy the code