首页 > 解决方案 > 条件系列失败 - Chart.js

问题描述

我有一个我一直在研究的基本多系列折线图。我想完成类似于下面代码的事情。

这些在我的里面datasets[]

            {label: 'Branch '+b7,
            data: B7,
            fill: false,
            backgroundColor: 'rgb(0, 0, 0)',
            borderColor: 'rgb(0, 0, 0)',
            },
            if(b8){
                {label: 'Branch '+b8,
                data: B8,
                fill: false,
                backgroundColor: 'rgb(0, 0, 0)',
                borderColor: 'rgb(0, 0, 0)',
                },
            }
            if(b9){
                {label: 'Branch '+b9,
                data: B9,
                fill: false,
                backgroundColor: 'rgb(0, 0, 0)',
                borderColor: 'rgb(0, 0, 0)',
                },
            }

如您所见,我只希望在b变量存在的情况下创建某些系列。datasets由于括号,这目前不起作用。

b除了将所有可能的变量设置为零之外,我还没有找到解决方案。这对我来说是不能接受的。

编辑 1

我想我会尝试datasets[]像下面这样创建多个。但是现在我无法使条件语句起作用。因为b0它告诉我出乎意料typeof

if(typeof b0 !== 'undefined'){
    datasets: [
    {label: 'Branch '+b0,
    data: B0,
    fill: false,
    backgroundColor: 'rgb(204, 0, 0)',
    borderColor: 'rgb(204, 0, 0)',
    }]
},
if(b1){
    datasets: [ 
    {label: 'Branch '+b1,
    data: B1,
    fill: false,
    backgroundColor: 'rgb(82, 235, 52)',
    borderColor: 'rgb(82, 235, 52)',
    }]
},

编辑 2

我尝试了很多方法来做这个if陈述。每次尝试都还没有奏效。我已经尝试if(typeof b !== 'undefined)'过以及设置xtrue或尝试的false结果。typeof bif(x===true)

标签: javascriptchart.js

解决方案


您尝试的不是有效的 javascript 语法,因为您不能将if语句放在对象声明的中间。尝试更多类似的东西:

var datasets = [
    {
        label: 'Branch '+b7,
        data: B7,
        fill: false,
        backgroundColor: 'rgb(0, 0, 0)',
        borderColor: 'rgb(0, 0, 0)'
    }
];
if(b8) {
    datasets.push({
        label: 'Branch '+b8,
        data: B8,
        fill: false,
        backgroundColor: 'rgb(0, 0, 0)',
        borderColor: 'rgb(0, 0, 0)',
    });
}
if(b9){
    datasets.push({
        label: 'Branch '+b9,
        data: B9,
        fill: false,
        backgroundColor: 'rgb(0, 0, 0)',
        borderColor: 'rgb(0, 0, 0)',
   });
}

new Chart(document.getElementById('chart'),{
    type: 'line',
    data: {
        labels: time,
        datasets: datasets
    }
});

推荐阅读