简体   繁体   English

带对象和基元的js数组克隆

[英]clone js array w/ objects and primitives

Given the array: 给定数组:

['1', {type:'2'}, ['3', {number: '4'}], '5']

I need to make a clone without using the slice , json.parse and other methods. 我需要使用slicejson.parse和其他方法进行克隆。

At the moment, the code is working, but it will not clone objects: 目前,该代码正在运行,但不会克隆对象:

var myArr =['1',{type:'2'},['3',{number:'4'}],'5'];
var arrClone=[];
for(var i=0;i<myArr.length;i++){
if(typeof(myArr[i])==='object')
{
    var arr=[];
    for(var j=0;j<myArr[i].length;j++){
        arr[j]=myArr[i][j];
    }


    arrClone[i]=arr;
}else { arrClone[i]=myArr[i]}

}

You could check if an object is supplied and if so, another check is made for an array. 您可以检查是否提供了对象,如果提供了,则对数组进行另一次检查。 Then retrn either the cloned array or the object, or the value itself. 然后撤消克隆的数组或对象,或值本身。

 function getClone(value) { if (value && typeof value === 'object') { return Array.isArray(value) ? value.map(getClone) : Object.assign( ...Object.entries(value).map(([k, v]) => ({ [k]: getClone(v) })) ); } return value; } var data = ['1', { type: '2' }, ['3', { number: '4' }], '5'], clone = getClone(data); console.log(getClone(data)); 

Here is a simple implementation without Array methods: 这是一个没有Array方法的简单实现:

 function deepClone(obj) { if (typeof obj !== "object" || obj === null) return obj; // primitives // It could be an array or plain object const result = obj.constructor.name == "Array" ? [] : {}; for (const key in obj) { result[key] = deepClone(obj[key]); // recursive call } return result; } // Demo var myArr =['1',{type:'2'},['3',{number:'4'}],'5']; var arrClone = deepClone(myArr); console.log(arrClone); 

Note that this only works for simple data types. 请注意,这仅适用于简单数据类型。 As soon as you start to work with Dates, regex objects, Sets, Maps, ...etc, you need much more logic. 一旦开始使用日期,正则表达式对象,集合,地图等,您就需要更多的逻辑。 Also think of self references and functions, and how they should be dealt with. 还应考虑自我参考和功能,以及应如何处理它们。

For more advanced cloning see How to Deep Clone in JavaScript , but expect the use of several methods. 有关更高级的克隆,请参见“ 如何在JavaScript中进行深度克隆” ,但希望使用多种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM