简体   繁体   中英

Can someone explain the following Javascript code in d3.js?

var bar = chart.selectAll("g")
               .data(data)
               .enter().append("g")
               .attr("transform", function(d, i) 
               { 
                 return "translate(0," + i * barHeight + ")"; 
               });

Can someone explain that why we should put the "+" before and after i * barHeight ?

this will set the transform attribute of each element of the "g" collection according to the index of element.

eg: if barHeight = 10

<g tranform="tranlate(0, 0)"/>
<g tranform="tranlate(0, 10)"/>
<g tranform="tranlate(0, 20)"/>
<g tranform="tranlate(0, 30)"/>
<g tranform="tranlate(0, 40)"/>

It helps to format the code.

var bar = chart.selectAll("g") 
.data(data) 
.enter().append("g") 
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

The answer has nothing to do with d3. It's just how you make strings with variables in javascript. Equivalent to something like this:

var name = "Johnny"
console.log("Hello " + name + " how are you today?")
//Hello Johnny how are you today?

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