gpt4 book ai didi

javascript - 如何理解 `constant(_), histogram`( `histogram.value`源代码的一部分)中的 `d3.histogram`?

转载 作者:行者123 更新时间:2023-11-28 15:07:46 26 4
gpt4 key购买 nike

我正在通过阅读 doc 和 src 来学习 d3-​​array。 histogram.value's doc很详细,但我还是觉得很难掌握。 The source code有助于更好地理解文档,但我仍然不太确定我是否正确理解了逻辑,主要是由于使用了 constant(_), histogram 以下行,特别是:

(value = typeof _ === "function" ? _ : constant(_), histogram)

这是我对histogram.value(value)的理解:

histogram.value = function(_) {
return arguments.length ? (value = typeof _ === "function" ? _ : constant(_), histogram) : value;
};
  1. 此代码的目的是使用identity或其他函数设置.value
  2. 如果没有给出参数,则使用identity函数
  3. 如果给出了 arg 并且 arg 是一个函数,则使用这个函数
  4. 如果arg不是函数,则将值设置为constant(_),其中_代表arg;但这部分代码是constant(_), histogram,我不明白为什么这里有一个histogram,也无法弄清楚constant到底是什么(_) 想做。

顺便说一句,constant(_),直方图comma operator 的使用?如果是,这如何有助于理解上面的代码?

<小时/>

阅读@Mark和@zerkms的回答后,我对以下两行代码的理解如下:

  1. @Mark 的代码

    d3.histogram() .value(someFunc) .domain(某个域) .thresholds(someThresholds);

可以很好地为 .value.domain.thresholds 设置新的自定义函数;

  • 以下代码会导致错误

    d3.histogram() 。值(value)() 。领域() .thresholds();

  • 因为正如@Mark在第一点中所做的并在@zerkms重写的代码中清楚地演示的那样,当没有arg时,.value仅返回identity函数,不返回直方图。因此,不再可能进行链接。

    但是我们可以通过以下代码访问d3.histogram的默认函数:

    d3.histogram().value();
    d3.histogram().domain();
    d3.histogram().thresholds();

    这是正确的吗?

    非常感谢!

    最佳答案

    代码分解如下:

    1. 如果没有给出 arg,则返回 value 的当前值。
    2. 如果给出了 arg 并且它是一个函数,则将值设置为 arg 并返回直方图函数。
    3. 如果给出了 arg 并且它不是函数,则将值设置为返回 arg 并返回直方图函数的函数。

    这里有两个令人困惑的部分:constant(_) 是什么以及为什么我们要返回直方图

    constant(_) 只是创建一个函数,调用时将返回 arg。

    返回直方图正在将外部函数返回到value。返回它是为了允许函数链接,并且允许您执行此操作:

    d3.histogram()
    .value(someFunc)
    .domain(someDomain)
    .thresholds(someThresholds);

    由于每个函数都返回父函数,因此您可以继续在调用的基础上进行构建...

    <小时/>

    评论编辑:

    是的,这将返回这些方法的默认值。从源代码来看:

    var value = identity,
    domain = extent,
    threshold = sturges;

    您可以在控制台上自行检查:

    > d3.histogram().value()
    function f(t){return t}
    > d3.histogram().domain()
    function c(t,n){var e,r,i,o=-1,u=t.length;if(null==n){for(;++o<u;)if(null!=(r=t[o])&&r>=r){e=i=r;break}for(;++o<u;)null!=(r=t[o])&&(e>r&&(e=r),i<r&&(i=r))}else{for(;++o<u;)if(null!=(r=n(t[o],o,t))&&r>…
    > d3.histogram().thresholds()
    function d(t){return Math.ceil(Math.log(t.length)/Math.LN2)+1}

    关于javascript - 如何理解 `constant(_), histogram`( `histogram.value`源代码的一部分)中的 `d3.histogram`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175287/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com