以下代码应该用bar扩展foo,赋值是找到" bug"在这个片段中,但对于我的生活,我似乎无法找到这个bug。有什么我想念的吗?在使用其他对象扩展对象时,此代码会中断的一些主要情况?
var foo = {a:1,b:"2",c:[3]}, bar = {d:"3",e:4,f:5.0};
var extend = function (obj, extension) {
if (typeof obj === "object" && typeof extension === "object") {
for (var i in extension) {
if (extension.hasOwnProperty(i) && !obj.hasOwnProperty(i)) {
obj[i] = extension[i];
}
}
return obj;
}
}
var foo_bar = extend(foo,bar);
console.log(foo_bar); //this logs as expected
答案 0 :(得分:0)
当你在两个物体中重复按键时,可能就是这样。扩展对象是否能够覆盖扩展对象的属性?
var foo = {a:1,b:"2",c:[3]}, bar = {c:"3",d:4,e:5.0};
var foo_bar = extend(foo,bar); //will result in {a:1,b:"2",c:"3",d:4,e:5.0};