demo999 89 demo999 89 - 19 days ago 6
Javascript Question

Adding variable to a array in javascript

I am trying to add parameters to a function in javascript, but it doesnt work somehow.

Can you let me know, how can I add them ?

I have a function like :

var foo = function () {
var a = {
"abc":"value1"
"bcd":"value2"
}
return a;
};


Now, I do this :

alert(data: [foo()]) // Actually I keep it in my function and **it works**


And I can see "abcd" and "bcd" with values.

But, Now I want to add a more variable (which is dynamic), how can I do that

I try this :

data:[foo() + {"cde":"value3"}] //doesnt work
data:[foo().push ({"cde"="value3"})] //doesnt work


How can I add a more variable to this array

Answer

The foo is a function that returns an object not an array. So there isn't any push method. If you want to add a new property to the object that foo returns you can do so as below:

// keep a reference to the object that foo returns
var obj = foo();
obj["cde"] = "value3";

or using dot notation as

obj.cde = "value3";

var foo = function () {
    var a = {
        "abc":"value1",
        "bcd":"value2"
    }
    return a;
};

var obj = foo();
obj["cde"] = "value3";

console.log(obj);

Comments