Javascript:如何将子对象追加到对象中?

时间:2015-01-03 02:58:08

标签: javascript object append subobject

我尝试了几件事,包括使用构造函数和下面的代码,但都没有。我觉得这很简单,我该怎么做?

<!DOCTYPE html>
<html>
<body>

<p>Creating a JavaScript Object.</p>

<p id="demo"></p>

<script>
var name ={ // subobject
    firstName : "John",
    lastName  : "Doe",
};
var person = {
name: {} // want to append here
};
person.name = name;
document.getElementById("demo").innerHTML =
person.name.firstName + " " + person.name.lastName;
</script>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

只需使用变量或子对象本身:

var person = {
    name: name
};

或者如果你使用子对象,

var person = { 
    name: { // subobject
        firstName : "John",
        lastName  : "Doe",
    }
};