其实我的办法并不是很好,不过好歹是自己琢磨的,,最开始的思路也是来自网上,就是不区分数组和类,统一只拷贝属性,但我在使用中发现如果拷贝对象是数组或者类的某个属性是数组的话,拷贝过去之后的数组全都无法用下标去访问了,于是我就简单的跟踪了下,发现简单的for each是不能拷贝Object本身的属性的,就是说,你new一个Object,然后给这个Object添加属性,然后用for each的方式去访问这个对象的属性的话,只能访问到后来添加的属性,而数组显然和Object不一样,所以仅仅只拷贝Object的方法就不能适应Array了,于是有了下面的代码:
这里我对怎么判断是不是数组没有找到好的办法。
function Clone(original)
{
if(typeof(original) == "object")
{
if (original.length != undefined)
{
return CloneArray(original);
}
return CloneObject(original);
}
return original;
}
function CloneObject(original)
{
var newObj = new Object();
for(var ele in original)
{
if(typeof(original[ele]) == "object")
{
if (original[ele].length != undefined)
{
newObj[ele] = CloneArray(original[ele]);
}
else
{
newObj[ele] = CloneObject(original[ele]);
}
}
else
{
newObj[ele] = original[ele];
}
}
return newObj;
}
function CloneArray(original)
{
var newArray = new Array();
for (var i = 0; i < original.length; i++)
{
if(typeof(original[i]) == "object")
{
if (original[i].length != undefined)
{
newArray[i] = CloneArray(original[i]);
}
else
{
newArray[i] = CloneObject(original[i]);
}
}
else
{
newArray[i] = original[i];
}
}
return newArray;
}
{
if(typeof(original) == "object")
{
if (original.length != undefined)
{
return CloneArray(original);
}
return CloneObject(original);
}
return original;
}
function CloneObject(original)
{
var newObj = new Object();
for(var ele in original)
{
if(typeof(original[ele]) == "object")
{
if (original[ele].length != undefined)
{
newObj[ele] = CloneArray(original[ele]);
}
else
{
newObj[ele] = CloneObject(original[ele]);
}
}
else
{
newObj[ele] = original[ele];
}
}
return newObj;
}
function CloneArray(original)
{
var newArray = new Array();
for (var i = 0; i < original.length; i++)
{
if(typeof(original[i]) == "object")
{
if (original[i].length != undefined)
{
newArray[i] = CloneArray(original[i]);
}
else
{
newArray[i] = CloneObject(original[i]);
}
}
else
{
newArray[i] = original[i];
}
}
return newArray;
}
这里我对怎么判断是不是数组没有找到好的办法。