gpt4 book ai didi

javascript - 无法在javascript中将对象属性复制到另一个

转载 作者:行者123 更新时间:2023-11-29 20:01:55 24 4
gpt4 key购买 nike

这应该很简单,但我在将一个对象的属性复制到另一个对象时遇到了问题。

var tableFormatting = {
table: {
style: {
width: "100px",
height: "100px"
},
border: "1px"
}
//similar code for tbody, tr, td
};
var table = document.createElement('table');
for (var p in tableFormatting.table)
table[p] = tableFormatting.table[p];
alert(table.style.width); //shows nothing. can't access it
alert(typeof(table.style.width)); //shows string, so i know it was copied or has a reference
alert(table.border); //shows 1px. this one is copied and accessible

为什么不显示样式属性?

最佳答案

你需要深拷贝它们

function copyValues( dst, src ) {
for( var key in src ) {
var value = src[key];
if( typeof value == "object" ) {
copyValues( dst[key], value );
}
else {
dst[key] = value;
}
}
}

copyValues( table, tableFormatting.table );

参见 http://jsfiddle.net/RpJKH/

否则,所发生的是手动等效于:

 table.style = obj.style

当然这什么都不做,因为 .style 是只读的。

关于javascript - 无法在javascript中将对象属性复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979887/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com