为什么使用键过滤器而不是columns.slice()?

时间:2017-03-24 06:19:19

标签: javascript d3.js

为什么作者使用

d3.keys(cars[0]).filter...

而不是使用

cars.columns.slice(1)

..?切片有效地返回相同的信息,而不必在下面做任何逻辑。

  var x = d3.scale.ordinal().rangePoints([0, width], 1),
   y = {};

  // Extract the list of dimensions and create a scale for each.
  x.domain(dimensions = d3.keys(cars[0]).filter(function(d) {
    return d != "name" && (y[d] = d3.scale.linear()
        .domain(d3.extent(cars, function(p) { return +p[d]; }))
        .range([height, 0]));
  }));

此数据为

name,economy (mpg),cylinders,displacement (cc),power (hp),weight (lb),0-60 mph (s),year
AMC Ambassador Brougham,13,8,360,175,3821,11,73
AMC Ambassador DPL,15,8,390,190,3850,8.5,70
AMC Ambassador SST,17,8,304,150,3672,11.5,72

来源:https://bl.ocks.org/mbostock/1341021

1 个答案:

答案 0 :(得分:5)

该代码的作者是D3的创建者。当然,他可能更喜欢第二个片段。但是,该代码使用D3 v3.x,并且在该版本的D3中数据数组中没有columns属性。

让我们在以下片段中看到这一点。

首先,使用D3 v3.x:



var data = d3.csv.parse(d3.select("#csv").text());

console.log("using d3.keys: " + d3.keys(data[0]));
console.log("using data.columns: " + data.columns);

pre{
  display: none;
}

<script src="https://d3js.org/d3.v3.min.js"></script>
<pre id="csv">name,economy (mpg),cylinders,displacement (cc),power (hp),weight (lb),0-60 mph (s),year
AMC Ambassador Brougham,13,8,360,175,3821,11,73
AMC Ambassador DPL,15,8,390,190,3850,8.5,70
AMC Ambassador SST,17,8,304,150,3672,11.5,72</pre>
&#13;
&#13;
&#13;

您可以看到d3.keys(data[0])有效,而data.columns返回未定义。

现在使用D3 v4.x:

&#13;
&#13;
var data = d3.csvParse(d3.select("#csv").text());

console.log("using d3.keys: " + d3.keys(data[0]));
console.log("using data.columns: " + data.columns);
&#13;
pre{
  display: none;
}
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">name,economy (mpg),cylinders,displacement (cc),power (hp),weight (lb),0-60 mph (s),year
AMC Ambassador Brougham,13,8,360,175,3821,11,73
AMC Ambassador DPL,15,8,390,190,3850,8.5,70
AMC Ambassador SST,17,8,304,150,3672,11.5,72</pre>
&#13;
&#13;
&#13;

d3.keys(data[0])data.columns都有效,并为您提供相同的结果。