javascript - 在 c3 中有条件地添加或省略 JavaScript 属性
问题描述
我正在使用单个函数来绑定多个C3图表。
使用仪表图类型时,需要一个阈值。此属性不适用于其他图表类型。
如何有条件地省略或添加阈值属性?
function bindChart(chartType) {
let chart = c3.generate({
bindto: '#Demo',
data: {
columns: [
['A', 95],
['B', 65],
['C', 11]
],
type: chartType,
},
color: {
pattern: ['#af5', '#ad3', '#a80', '#a00'],
threshold: {
values: [0, 50, 75, 100], //For gauge
}
},
});
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.min.js"></script>
<button onclick="bindChart('pie');">PIE</button>
<button onclick="bindChart('gauge');">GAUGE</button>
<button onclick="bindChart('bar');">BAR</button>
<div id="Demo" />
解决方案
您可以首先使用所有公共键构建一个对象,然后您可以有条件地添加您可能需要的任何新键。
function bindChart(chartType) {
// Build base object with common keys
let colorOptions = {
pattern: ['#af5', '#ad3', '#a80', '#a00']
};
// Assuming the check is for the chartType to be guage
if (chartType === 'gauge') {
// Conditionally add new keys
colorOptions.threshold = {
values: [0, 50, 75, 100], //For gauge
}
}
let chart = c3.generate({
bindto: '#Demo',
data: {
columns: [
['A', 95],
['B', 65],
['C', 11]
],
type: chartType,
},
color: colorOptions,
});
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/c3/0.5.4/c3.min.js"></script>
<button onclick="bindChart('pie');">PIE</button>
<button onclick="bindChart('gauge');">GAUGE</button>
<button onclick="bindChart('bar');">BAR</button>
<div id="Demo" />
推荐阅读
- python-3.x - Matplotlib 使用 twinx() - TypeError: 'AxesSubplot' 对象不支持项目分配
- android - Visualizer 在使用排队的 MediaPlayer 时返回全零
- linux - 我可以使用脚本将我的终端环境更改为 bash shell,然后在同一脚本中更改 shell 后执行其他命令吗?
- node.js - Socket.io 没有在 Heroku 上为每个连接生成唯一的套接字 ID
- python - Python:将方法结果分配给构造函数上的实例变量时出错
- sql - ORA-01417: 一个表最多可以外部连接到另一个表
- excel - 如何识别受密码保护的只读文件?
- python - Plotly:如何修复树状图留下大的空白空间?
- php - 如何检测PHP中关联数组迭代中的最后一个元素
- python - 如何停止在 django 中拥有匿名用户