使用函数向JS Object Literal添加属性
Adding Attributes to JS Object Literal with a Function
我正试图使用函数向我的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.defineProperty
(MDN)方法轻松实现您想要的内容:
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>";
}
相关文章:
- 正在添加'X'按钮,在文本字段旁边使用javascript
- 如何在映射数组中添加换行符
- 正在将数据主题添加到所有项目
- ZeroClipboard-在复制之前添加到值
- 我可以在json对象中添加一个函数吗
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 正在SharePoint 2013母版页中添加JQuery移动文件
- 如何添加浮动和非浮动,其他
- 添加文字和评论功能更新Div
- 如果使用 lodash 将属性存在于另一个对象中,则向对象添加属性
- 动态地改变“”的URL;添加新项目”;链接使用javascript/jquery
- 在函数中添加数组元素的数值
- 如何将歌曲添加到jPlayer
- 在html Select中添加搜索
- Java脚本时间添加
- FabricJs-限制主对象内添加对象的移动区域
- JQuery添加元素需要在我的js之前再次添加JQuery脚本
- 使用函数向JS Object Literal添加属性
- Reset All按钮从JS literal添加一个新的实例jQuery
- 添加"literal HTML"转换为一个HTML小部件,其中包含来自数据源的数据