JavaScript / D3:“相同”函数调用产生不同的结果? [英] JavaScript/D3: The "same" function call yields different result?

查看:133
本文介绍了JavaScript / D3:“相同”函数调用产生不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是关于的混淆( jsfiddle-demo ) /github.com/mbostock/d3/wiki/Ordinal-Scales#wiki-category10rel =nofollow> category10 函数 D3

Here is my confusion(jsfiddle-demo) about the category10 function in D3:

> var a = d3.scale.category10()
> a(0)
"#1f77b4"
> a(10) //the expected different color value
"#2ca02c"

直接调用 category10 的返回函数,事情就像这样

If I call directly the returned function of calling category10 , things go like this

> d3.scale.category10()(0)
"#1f77b4"
> d3.scale.category10()(10) //the SAME color! Why?
"#1f77b4"

在我看来,调用 d3。 scale.category10()(10)应该产生与调用 a(10)相同的值。

In my opinion, calling d3.scale.category10()(10) should yield the same value as calling a(10).

这里出现了什么问题?

推荐答案

每次调用 d3.scale.category10 ()返回一个新的ordinal scale实例,所以通过调用 d3.scale.category10()(10)每一次。每个顺序缩放实例都可以使用输入域(将输入值映射到输出颜色)显式配置,也可以隐式地进行配置,只返回第一个输入值的第一个颜色,依此类推,创建映射你使用它。

Each call to d3.scale.category10() returns a new ordinal scale instance, so by calling it like d3.scale.category10()(10) you are using a new instance each time. Each ordinal scale instance can either be explicitly configured with an input domain (mapping input values to output colors), or it can do so implicitly, where it just returns the first color for the first input value, and so on, creating the mapping as you use it.

在你的例子中,你使用每个调用一个新的实例,所以无论你输入什么值,你都会得到第一个颜色。即使您早期的示例可能会导致一些意外的行为,除非您显式配置输入域。例如:

In your example you're using a new instance with each call, so no matter what value you input, you will get the first color back. Even your earlier examples might lead to some unexpected behavior unless you explicitly configure the input domain. For example:

var a = d3.scale.category10()
a(0)  // => "#1f77b4"
a(10) // => "#ff7f0e"
var b = d3.scale.category10()
b(10) // => "#1f77b4"
b(0) // => "#ff7f0e"

这里是如何设置输入域总是返回第N个颜色N无论以什么顺序进行调用:

Here's how you can set the input domain to always return the Nth color whenever you input N no matter what order you make the calls:

var a = d3.scale.category10().domain(d3.range(0,10));
a(0)  // => "#1f77b4"
a(1)  // => "#ff7f0e"
a(2)  // => "#2ca02c"
var b = d3.scale.category10().domain(d3.range(0,10));
b(2)  // => "#2ca02c"
b(1)  // => "#ff7f0e"
b(0)  // => "#1f77b4"

BTW,即使现在返回与 a(0)相同,但是这是因为10超出范围[0,10],从0开始到结束9,所以 a(10)是一个未分配的输入,并获得下一个颜色,这恰好是第一个颜色。

BTW, as an aside, even now a(10) returns the same as a(0) but that's because 10 is outside the range [0,10], which starts at 0 and ends at 9, so a(10) is an unassigned input and gets the next color, which happens to be the first.

这篇关于JavaScript / D3:“相同”函数调用产生不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆