这是一个好的克隆功能吗?
这是一个可以递归克隆对象的克隆函数吗?
function clone(o)
{
function CloneObject(inObj)
{
for (i in inObj)
{
if(typeof inObj[i] == 'object')
this[i] = clone(inObj[i]);
else
this[i] = inObj[i];
}
}
return new CloneObject(o);
}
另外,我发现这不适用于数组。如何克隆数组?
Is this an okay clone function for cloning an object recursively?
function clone(o)
{
function CloneObject(inObj)
{
for (i in inObj)
{
if(typeof inObj[i] == 'object')
this[i] = clone(inObj[i]);
else
this[i] = inObj[i];
}
}
return new CloneObject(o);
}
Also, i found out this doesn't work with arrays. How can I clone an array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它当然不会完美地克隆对象 - 克隆不会具有原始对象的原型,并且它们将具有不同的构造函数,并且如果原始对象具有任何不可迭代的属性,那么这不会复制它们 - 但你问如果它是“好的”,那么答案很可能是“是”:如果它所做的就是您需要它做的所有事情,那么它绝对没问题。
至于克隆数组 - 您可以检查是否
inObj.constructor == Array
。It certainly doesn't clone the object perfectly — the clone won't have the original's prototype, and they'll have different constructors, and if the original has any non-iterable properties, then this won't copy them — but you ask if it's "okay", and the answer to that may well be "yes": If what it does is all that you need it to do, then it's absolutely fine.
As for cloning arrays — you could check if
inObj.constructor == Array
.