2

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

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 

为什么不显示样式属性?

4

1 回答 1

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

于 2012-12-20T20:24:25.523 回答