在创建时增加javascript对象名称?

时间:2017-02-26 23:32:54

标签: javascript jquery

我正在创建3个具有相同名称和选项的对象,但它们可以具有不同的值。这些对象是根据用户的输入动态创建的,因此我无法对它们进行不同的命名,因为我试图根据它们的计数或递增的值来引用它们。

我现在的问题是我同时创建了3个对象,类似于:

var contentformat = { name:"Test Title 1", 
                      description:"A 5 minute video",
                      icon: ""
                    };

var contentformat = { name:"Test Title 2", 
                      description:"A 3 minute video",
                      icon: ""
                    };

var contentformat = { name:"Test Title 3", 
                      description:"A 10 minute video",
                      icon: ""
                    };

但是如果我在我的控制台中检查它们,它只显示“测试标题3”对象。有没有办法可以拥有这些多个对象(或者在创建时增加它们?)

3 个答案:

答案 0 :(得分:3)

变量一次只能容纳一个值。因此,存储的唯一对象是您分配给contentformat的第三个也是最后一个。请尝试使用数组。

编辑:看起来OP提到对象是在不同的地方创建的。这是使用Array#push(...elements)的理想场所。



var contentformat = []

// Add a single item
contentformat.push({
  name: "Test Title 1",
  description: "A 5 minute video",
  icon: ""
})

// Add multiple items at once
contentformat.push({
  name: "Test Title 2",
  description: "A 3 minute video",
  icon: ""
}, {
  name: "Test Title 3",
  description: "A 10 minute video",
  icon: ""
})

// Get all three items back!
console.log(contentformat)




编辑:只是为了记录,问题的根源有点不同。通过一些jQuery DOM操作解决了这个问题:

window.contentformat = []

$('.hs_cos_wrapper_widget').each(function (i) {
  $(this).addClass('tabpanel').attr('id', 'tab' + (i + 1))
  contentformat.push({
    title: $(this).find('.cf_title').text(),
    description: $(this).find('.cf_description').text()
  })
})

答案 1 :(得分:0)

你可以创建一个为你创建一个对象的函数,它依赖于这样的全局计数器:

var COUNTER = 0;                // the counter (must be outside the function and must be initialized)
function creator(desc, icon) {  // take a description and an icon and returns an object
  COUNTER++;                    // increment the counter
  return {
    name: "Test title " + COUNTER,
    description: desc,
    icon: icon
  };
}


console.log(creator("some desc", ""));
console.log(creator("some other desc", ""));
console.log(creator("yet another desc", "icooon"));
// ...

答案 2 :(得分:0)

您对所有三个使用相同的变量名称,因此它将使用新值替换早期值,这就是您仅查看最后一个值的原因。

你应该使用数组。

var sample = new Array();
sample [0] = { name:"Test Title 1", 
                  description:"A 5 minute video",
                  icon:""};
sample [1] = { name:"Test Title 2", 
                  description:"A 3 minute video",
                  icon:""};
sample [2] = { name:"Test Title 3", 
                  description:"A 10 minute video",
                  icon:""};

然后您可以使用索引访问数组元素,如下所示。

 var video1 = sample [0];

这可以解决您的问题。