1

I don't completely understand how to use method chaining with functions. Below are some cases

Expected Case

var dataset = [ 5, 10];

function count(d) {
  return "I can count up to " + d ; 
}
            d3.select("body").selectAll("p")
                .data(dataset)
                .enter()
                .append("p")
                .text(count);

Output

I can count up to 5

I can count up to 10

What I don't get is this output from a modified count function

function count(d, a) {
  return "I can count up to " + d + a ; 
}

Output

I can count up to 50

I can count up to 101

Read this post but I'm still missing something. Should I just reread it?

How are input parameters filled in javascript method chains?

1
  • 2
    Apparently, the index of the element is passed as the second parameter. So, the first time you get 50 which is actually '5' + '0' and then 101 is '10' + '1'
    – Bali Balo
    Dec 22, 2014 at 0:09

1 Answer 1

0

When you call a function in d3.js .text its signature is:

.text(function(datum, index){

 });

So:

return "I can count up to " + d + a ; 

means:

return string + datum + index.  

Finally, with Javascript, when you start with a string first, everything is coerced into a string so the d + a concatenates 5 and 0 and then 10 and 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.