简体   繁体   中英

What does .data(function(d) { return d; }) return in d3?

var matrix = [
  [11975,  5871, 8916, 2868],
  [ 1951, 10048, 2060, 6171],
  [ 8010, 16145, 8090, 8045],
  [ 1013,   990,  940, 6907]
];

var tr = d3.select("body").append("table").selectAll("tr")
    .data(matrix)
  .enter().append("tr");

var td = tr.selectAll("td")
    .data(function(d) { return d; })
  .enter().append("td")
    .text(function(d) { return d; });

I don't understand what d is representing here. Could someone so kindly walk me through the code?

Reference: https://github.com/mbostock/d3/wiki/Selections#wiki-remove

What you have here is a nested selection , ie you're making a selection and then a selection based on that. This is also the explanation for the function in the .data() argument -- it is nested below the first, so it can refer to it.

In particular, you're passing in an array of arrays in .data(matrix) . D3 will do something for every element of that matrix, ie for every array. Here, it is bound to the appended tr elements. So then when you call .data() again, you can refer to the data bound to those elements (the tr s). function(d) { return d; } function(d) { return d; } is simply saying that D3 should use the data already bound to it. As that is an array, D3 will do something for every element of it, ie append the table cell elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM