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

时间:2012-12-20 20:21:46

标签: javascript object properties copying

这应该很简单,但我无法将对象的属性复制到另一个。

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 

为什么样式属性不显示?

1 个答案:

答案 0 :(得分:3)

你需要深层复制它们

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是只读的。