使用函数向JS Object Literal添加属性

Adding Attributes to JS Object Literal with a Function

本文关键字:Literal 添加 属性 Object JS 函数      更新时间:2023-09-26

我正试图使用函数向我的JS对象添加一个"attribute":"value",但遇到了问题。我希望你们中的一些人能帮忙。

允许我创建上下文。。。

这是我的对象,它本身位于我的文件"myobject.js"中:

var myObject = {
'12-25-2012' = '<p>Christmas</p>', 
'07-18-2013' = '<p>My Birthday</p>' 
};

现在,我得到了一些要添加到对象中的更多信息。我知道我可以通过在脚本标记或对象下面的myobject.js文件中插入以下内容来完成:

var theDate = '07-23-2013'; 
myObject[theDate] = "<p>Mom's Birthday</p>";

但这不是我想要的。为了这个上下文,我想添加完全相同的信息,用一个函数命名为myFunction()。原因是,在应用程序中,我希望能够将参数传递给函数,该函数将定义对象的新属性和值。

这是我尝试过的,但不起作用:

function myFunction(){
var theDate = '07-23-2013'; 
myObject[theDate] = "<p>Mom's Birthday</p>";
}

有什么想法吗?非常感谢您的帮助!!

我不建议在Object类型的变量上使用括号[]

此外,必须使用attribute : value表示法在对象中定义属性/属性,因此不使用等号

您可以使用Object.definePropertyMDN)方法轻松实现您想要的内容:

JavaScript

var myObject = {
    '12-25-2012': '<p>Christmas</p>',
    '07-18-2013': '<p>My Birthday</p>'
};

function myFunction(attribute,value) {
    Object.defineProperty(myObject, attribute, {
        value: value,
        /* This lets you overwrite the value later */
        writable: true,
        /* This lets you see the attribute in the Object attributes/properties list and in the length too */
        enumerable: true,
    });
    return myObject;
}
/* Displaying the content of the Object */
console.dir(myFunction("07-23-2013","<p>Mom's Birthday</p>"));
alert(JSON.stringify(myObject,null,4));

所以您这样调用函数:myFunction(TheDate, TheValue);

实时演示

您的JSON格式中有一个错误。。分隔符是CCD_ 6而不是CCD_。

下面是创建对象的示例。第一次访问myObject['07-23-2013']undefined

第二次存在是因为调用了myFunction()

JSFiddle:http://jsfiddle.net/KuFKU/

示例:

  var myObject = {
    '12-25-2012':'<p>Christmas</p>', 
    '07-18-2013':'<p>My Birthday</p>' 
};
alert("This exists:"+myObject['12-25-2012']);
alert("This is undefined:"+myObject['07-23-2013']);
myFunction();
alert("This is now defined:"+myObject['07-23-2013']);
function myFunction(){
var theDate = '07-23-2013'; 
myObject[theDate] = "<p>Mom's Birthday</p>";
}