1
为什么b.first [0]返回“t”,我该如何避免这种情况?对象JavaScript中的奇怪行为数组
我需要安全的“Q”在b.first [0]
var extend = function(o,p){
for(prop in p){
o[prop] = p[prop];
}
return o;
};
var a = {first:['q','w']};
var b = {};
extend(b,a);
document.write(a.first[0]); //q
document.write(b.first[0]); //q
a.first[0] = 't';
document.write(a.first[0]); // t
document.write(b.first[0]); // t ?????????????????????
因为'a.first'是对数组的引用。当分配'b.first = a.first'(这就是* extend *似乎要做的事情)时,'b'获得对同一个数组的引用。 – RobG 2013-04-05 05:57:07
你需要**对象的深**拷贝。 http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-a-javascript-object/122704#122704 – HerrSerker 2013-04-05 06:02:36
在我使用一些deepExtend的真实的,但似乎我的版本不好。我会尝试其他版本。谢谢! – Aleksey 2013-04-05 06:35:43