首页 > 解决方案 > 在 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" />

标签: javascriptd3.jschartspropertiesc3.js

解决方案


您可以首先使用所有公共键构建一个对象,然后您可以有条件地添加您可能需要的任何新键。

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


推荐阅读