我正在尝试以编程方式创建此对象:
var data = {
"player0": {
"name": "kahn",
"pos": "gk",
"ability": "best",
"unsure": 0,
"waiting": 1
},
"player1": {
"name" : "recoba",
"pos": "cmf",
"ability": "inter",
"unsure": 1,
"waiting": 0
}
};
这是我的尝试,但出现标题中显示的错误:
var test;
test.player.name = "kahn";
test.player.pos = "gk"; // enough properties for testing
console.log(test);
我该怎么办?
最佳答案
在创建对象本身之前,您无法分配对象属性:
var test = {};
test.player = {};
test.player.name = "kahn";
...
console.log(JSON.stringify(test));
要么:
var test = {};
test.player = {name: "kahn", pos: "gk"};
console.log(JSON.stringify(test));
要么:
var test = [];
var player1 = {name: "kahn", pos: "gk"};
var player2 = {name: "recoba", pos: "cmf"};
test.push(player1);
test.push(player2);
console.log(JSON.stringify(test));
要么:
var test = {};
test.player0 = {name: "kahn", pos: "gk"};
test.player1 = {name: "recoba", pos: "cmf"};
console.log(JSON.stringify(test));
注意:后者对应于您所讨论的对象结构。
要么:
var test = {};
for (var i = 0; i < 5; i++) {
test["player" + i] = {"name": "player " + i};
...
}
console.log(JSON.stringify(test));
关于javascript - 未捕获的TypeError : Cannot read property 'player' of undefined,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32544962/