简体   繁体   English

在JavaScript中将变量添加到数组

[英]Adding variable to a array in javascript

I am trying to add parameters to a function in javascript, but it doesnt work somehow. 我正在尝试将参数添加到javascript中的函数,但是以某种方式无法正常工作。

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. 我可以看到带有值的“ abcd”和“ bcd”。

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 如何向此数组添加更多变量

The foo is a function that returns an object not an array. foo是一个返回对象而不是数组的函数。 So there isn't any push method. 因此,没有任何push方法。 If you want to add a new property to the object that foo returns you can do so as below: 如果要将新属性添加到foo返回的对象中,可以执行以下操作:

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

Why not try as below: 为什么不尝试如下:

var x = foo();
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 如果未传递任何参数,则可以使用rest parameterspread element Object.assign()返回a ,否则将传递的参数设置a对象

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM