简体   繁体   English

如何在JavaScript中传递变量?

[英]How to pass variable in a variable in JavaScript?

I want to define a variable that contains a variable. 我想定义一个包含变量的变量。 In this example the variable that I want to pass is "filldata". 在这个例子中,我想传递的变量是“filldata”。

I have tried passing it using $filldata as well as +filldata+. 我尝试使用$ filldata以及+ filldata +传递它。

if (fill == true) {
     $filldata = "fill: true,";
} else {
     $filldata = "fill: false,";
};

if (amount == true) {
        var set1 = {
            label: "Earnings",
            id: "earnings",
            data: data1,
            points: {
                show: true,
            },
            bars: {
                show: false,
                barWidth: 12,
                aling: 'center'
            },
            lines: {
                show: true,
                $filldata
            },
            yaxis: 1
        };
    } else {
        var set1 = "";
    }

Since you are just trying to create a boolean property named 'fill' with the value of some variable, also called fill (using fussy truthy/falsy values), then you can just skip creating the intermediate $filldata variable altogether and just create the property with the value evaluated inline. 由于您只是尝试使用某个变量的值创建名为“fill”的布尔属性,也称为fill(使用繁琐的truthy / falsy值),然后您可以跳过创建中间$ filldata变量并只创建属性使用内联评估的值。 It's more succinct and more obvious. 它更简洁,更明显。

Try: 尝试:

if (amount == true) {
    var set1 = {
        label: "Earnings",
        id: "earnings",
        data: data1,
        points: {
            show: true,
        },
        bars: {
            show: false,
            barWidth: 12,
            aling: 'center'
        },
        lines: {
            show: true,
            fill: fill==true
        },
        yaxis: 1
    };
} else {
    var set1 = "";
}

EDIT: 编辑:

Also, note that it is not good practice to declare the variable set1 inside the if block scope if you intend to use it elsewhere. 另外,请注意,如果您打算在其他地方使用变量set1,那么在if块范围内声明变量set1并不是一个好习惯。 A better alternative would be: 一个更好的选择是:

var set1 = (amount == true) ?
    {...your object as defined above...}
    : "";

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

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