Вопрос

I am trying to add an "attribute" : "value", to my JS Object using a function, but am having trouble. I'm hoping some of you might be able to help.

Allow me to create a context...

Here is my object which resides by itself in my file "myobject.js":

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

Now I've got some more information that I want to add to the object. I know that I can do it by inserting the following in script tags or in the myobject.js file below the object like this:

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

But that's not how I want it to happen. I want to add this exact same information, for the sake of this context, with a function which let's name myFunction(). The reason being, in application, I want to be able to pass parameters to the function which will define the object's new attribute's and values.

This is what I tried, but isn't working:

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

Any thoughts about what is going wrong? Help would be very much appreciated!!

Это было полезно?

Решение

I would discourage using brackets [] on Object type variables.

Also, you must define attributes/properties in an Object using the attribute : value notation, so there is no equal sign used.

You can easily achieve what you want using the Object.defineProperty(MDN) method:

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));

So you call the function this way : myFunction(TheDate, TheValue);

Live Demo

Другие советы

You have an error in your JSON format..delimiter is : and not =.

Below an example in which your object is created. The first time myObject['07-23-2013'] is accessed it is undefined.

The second time it is exists because myFunction() has been called.

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

Example:

  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>";
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top