简体   繁体   中英

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".

I have tried passing it using $filldata as well as +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. 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. A better alternative would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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