这可能是一个愚蠢的问题,但现在我无法弄清楚。所以我有需要。
我正在显示静态数据,但我希望将来能够保持动态。
var name = [];
name.push({ name: "Gareth" });
name[0].push({ name: "john" }); // This statement doesn't work as name[0]!=[] I guess.
name[0].push({name:"dolly"});
我希望得到像,
+name <--- expandable
+0 <--- expandable
name : "gareth"
+0 <--- expandable
name: "john"
+1 <--- expandable
name: "dolly"
我知道这并不困难。但我现在无法弄明白。非常感谢帮助。
答案 0 :(得分:1)
你不能push
name[0]
上的任何内容,因为它不是数组,但您仍然可以为其分配带数字的元素并创建自己的推送。
var makePushable = function (obj) {
obj.push = function (item) {
this[this.length] = item;
this.length++;
};
obj.length = 0; //Keep track of how many elements
}
var name = [];
name.push({ name: "Gareth" });
makePushable(name[0]);
name[0].push({ name: "john" });
name[0].push({ name:"dolly" });
我们得到:
name[0] ---> {
name:"gareth",
0: {name:"john"},
1: {name:"dolly"},
length: 2,
push: function () { ... }
}
name[0][0] ---> {name:"john"}
name[0][1] ---> {name:"dolly"}
如果您不希望push
和length
显示在for ( prop in xxx ) if (xxx.hasOwnProperty(prop))
上,您可以创建一个类似的类:
var Pushable = function (obj) {
for (var i in obj) {
this[i] = obj[i];
}
Object.setPrototypeOf(this, {
push: function (item) {
this[this.length] = item;
Object.getPrototypeOf(this).length++;
},
length: 0
});
};
Pushable.prototype.push = function (item) {
this[this.length] = item;
Object.getPrototypeOf(this).length++;
};
Pushable.prototype.length = 0;
var name = [];
name.push(new Pushable({ name:"Gareth" }));
name[0].push(new Pushable({ name: "john" }));
name[0].push(new Pushable({ name:"dolly" }));
name[0][1].push(new Pushable({ name:"last kid" }));
您可以制作push
功能,如果需要,可以自动为您创建Pushable
课程。
答案 1 :(得分:0)
首先更改你的名字 试试这个
var m = {}; m.name=[];
m.name.push({ name: "Gareth" });
m.name.push({ name: "john" }); // This statement doesn't work as name[0]!=[] I guess.
m.name.push({name:"dolly"});
out put