jQuery.extend
不受循环引用
的影响吗?
如何避免 Javascript 中的循环引用(在克隆或递归检查时)?仅检查当前目标在其属性列表中是否存在是不够的,因为它可能引用某些外部对象。
一种选择是保留迄今为止获取的所有对象
的另一个列表。但这会增加内存消耗并要求停止脚本吗?
并且我不想在工作线程中移动克隆操作。
最佳答案
老问题,但我今天正在寻找这个 - 答案是:不。
https://api.jquery.com/jquery.extend/
On a deep extend, Object and Array are extended, but object wrappers on primitive types such as String, Boolean, and Number are not. Deep-extending a cyclical data structure will result in an error.
For needs that fall outside of this behavior, write a custom extend method instead, or use a library like lodash.
lodash 文档不是很清楚,但是 _.cloneDeep 支持克隆循环引用。
https://lodash.com/docs/4.17.10#cloneDeep
您最好使用像 lodash 这样聪明的东西,因为我认为它会正确检测多次引用的所有对象,并创建整个对象图的真正克隆,所有循环引用都完好无损。
但是,这是一个简单的深度克隆,它使用简单的对象堆栈(在 TypeScript 中)简单地忽略循环引用:
public static DeepClone(source: any, stack: any[] = null): any
{
if (!source)
{
return source;
}
var result;
result = Array.isArray(source) ? [] : {};
for (var k in source)
{
var v = source[k];
if (typeof v === "object")
{
stack = stack || [];
// Just ignore circular references? Or, to be clever, maintain a
// dictionary of object references from the original graph linked to
// the new objects in the cloned graph, to preserve the full graph.
if (stack.indexOf(source) >= 0)
{
return null;
}
stack.push(source);
result[k] = this.DeepClone(v, stack);
stack.pop();
}
else
{
result[k] = v;
}
}
return result;
}
关于javascript - jQuery.extend 是否可以避免循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8355591/