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
-
Even if you are creating a C# application, if your question isn't related to C#, there's no benefit to tagging it.Jonesopolis– Jonesopolis2016年11月14日 20:20:02 +00:00Commented Nov 14, 2016 at 20:20
3 Answers 3
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
Why not try as below:
var x = foo();
x["newProp"] = 33;
2 Comments
x.newProp = 33?You can use rest parameter, spread element Object.assign() to return a if no parameters passed, else set passed parameters to a object
var foo = function foo(...props) {
var a = {
"abc": "value1",
"bcd": "value2"
}
// if no parameters passed return `a`
if (!props.length) return a;
// else set passed property at `a` object
return Object.assign(a, ...props);
};
var a = foo();
var b = foo({"cde":"value3"});
console.log(a, b);