javascript - 条件系列失败 - 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)'
过以及设置x
为true
或尝试的false
结果。typeof b
if(x===true)
解决方案
您尝试的不是有效的 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
}
});
推荐阅读
- java - 如何使用 Fragment View Pager 创建待办事项列表应用程序
- python-3.x - 循环遍历 json 对象并使用相同的键添加到字典并附加到列表
- mysql - 在 syntaq mysql 查询中出现错误“子查询返回超过 1 行”
- scala - 第一个 for-callback 几乎每次都打印未来列表,第二个 onComplete-callback 很少返回成功(从不失败)
- c# - 在 Xamarin.Froms 中显示 AdMob 横幅的问题
- python - Pyspark logistic Regression fit RDD object has no attribute _jdf error
- fusionauth - 这种 SSO 场景是否可以使用 FusionAuth?
- php - SELECT all tables from DB and query same column name in each one of them
- python - 如何跟踪各种类型的条纹
- javascript - 将用户输入与登录按钮链接