说我希望对象是这样的:
var Book = {
title: "the catcher in the rye",
price: "80.98",
characters: [{name: "holden caulfield", age: 16, height:"6.2"},
{name: "phoebe caulfield",age:13, height: "5"}]
};
EDITED
问题: characters数组是通过逐个添加一个字符来构建的。如何确保名称,年龄和身高属性的定义如上所述。
有什么效果?
Book.characters.add({name: "phoebe caulfield",age:13, height: "5"});
我希望能够以编程方式定义它,即向对象添加属性,而不是像这样定义它。
这可能吗?
答案 0 :(得分:6)
你可以在动态代码(而不是静态声明)中这样做:
var Book = {};
Book.title = "the catcher in the rye";
Book.price = "80.98";
Book.characters = [];
Book.characters.push({name: "holden caulfield", age: 16, height: "6.2"});
Book.characters.push({name: "phoebe caulfield", age: 13, height: "5"});
答案 1 :(得分:2)
你的意思是这样吗?
var Book = {}; // empty object
Book.title = "the catcher in the rye";
Book.price = 80.98;
Book.characters = [];
var character = {
"name": "holden caulfield",
"age": 16,
"height": 6.2
};
Book.characters.push(character);
答案 2 :(得分:0)
var Book={};
Book.title="the catcher in the rye";
Book.price="80.98";
var characters=[];
characters.push({name: "holden caulfield", age: 16, height:"6.2"});
characters.push({name: "phoebe caulfield",age:13, height: "5"});
Book.characters=characters;
...等
答案 3 :(得分:0)
当然是! Javascript是一种完全动态的语言 - 如果你想要一个对象的新属性,只需设置它!
e.g。
var myObject = {}; // empty object
myObject.myProperty = 5; // creates the new property and sets it to 5.
myObject.nestedObject = { prop1: 6, 'long-property-name': 'lolcats' };
答案 4 :(得分:0)
我认为你正在寻找一个JSON字符串: http://www.json.org/js.html
这将允许您创建对象:
var myobj = { };
myobj.myprop = "value";
alert(JSON.stringify(myobj));
答案 5 :(得分:0)
使用map函数是我发现构建对象数组的最简单方法。下面的代码片段仅用2条语句即可构建所需的对象:
var Book = {
title: "the catcher in the rye",
price: 80.98
};
Book.characters = [6.2, 5].map(el => {
return {
name: 'caulfield', age: 14, height: el
};
});
// Output
JSON.stringify(Book);
{
"title": "the catcher in the rye",
"price": 80.98,
"characters": [
{ "name":"caulfield", "age":14, "height":6.2 },
{ "name":"caulfield", "age":14, "height":5 }
]
}