如何附加到空的JSON对象?

时间:2011-09-08 03:19:41

标签: javascript json

  var kids = [{}];
  i = 0;
  while (i++ !== count) {
    child = {
      value: Math.floor(Math.random() * 100),
      children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log( kids );
  }

问题是kids对象有一个空的第一个元素。我怎么能绕过它呢?如果我不将其声明为JSON对象,则无法访问push元素。

由于

4 个答案:

答案 0 :(得分:10)

将孩子宣布为空数组:

var kids = [];

答案 1 :(得分:3)

听起来您希望最终得到一个JavaScript对象,其中包含多个具有两个键valuechildren的对象实例。看起来阵列是最好的选择(Khnle和Chris的答案会给你):

[{"value":2,"children":3}, {"value":12,"children":9}, {"value":20,"children":13}]

然而,在你对其中一个答案的评论中,你说你不想要一个数组。一种方法是将其包裹起来,如Jergason的回答:

{
    "children": [
        {"value":2,"children":3}, 
        {"value":12,"children":9}, 
        {"value":20,"children":13}
    ]
}

您的问题似乎表明您喜欢数组,因为您获得了push操作,但您希望完全避免它们。 完全避免数组的唯一方法是使用自己的唯一键标记每个对象。如果这确实是你想要的,它将是这样的:

{
    "child0":{"value":2,"children":3}, 
    "child1":{"value":12,"children":9}, 
    "child2":{"value":20,"children":13}
}

这不难做到;只需将kids.push(child)替换为kids["child" + i] = child

确保这真的是你想要的,但是,因为这个孩子的集合真的似乎尖叫“阵列”! : - )

答案 2 :(得分:1)

你可以让你的对象包含一个空数组。

var obj = { "children": [] };
// Your looping code here
obj.children.push(child);

答案 3 :(得分:0)

稍微改变一下(为局部变量添加var):

var kids = []; //Note this line
var i = 0; //index counter most likely needs to be local
while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

我认为这就是你想要的。

更新:您的要求相当奇怪。你可以这样做:

 var kids = [{}]; //Note this line
 delete kids[0];
 var i = 0; //index counter most likely needs to be local
 while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

 var kids = [{
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
 }];
 var i = 1; //1 less iteration than previous
 while (i++ !== count) {
    var child = {
       value: Math.floor(Math.random() * 100),
       children: addChildren(Math.floor(Math.random() * 10))
    };
    kids.push(child);
    console.log(kids);
 }

这样可以满足你的要求,但我想,我想要的仍然是你想要的。

相关问题