【问题标题】:Trouble passing in additional parameters in function在函数中传递附加参数时遇到问题
【发布时间】:2019-08-07 06:04:02
【问题描述】:

我正在尝试在 d3 中编写一个函数,该函数将检查我的数据的“时间”并查看它是否介于另外两个时间之间,并进行相应的过滤。

//start with a function to check if time for each data point is in between two other times
function timeInterval(data, start, end) {
    var time = data.Time

    if (start <= time <= end) {           
        return "inline";
    } else {
        return "none";
    };   
 }

//set the display of points to either inline or none
function updateTime(value) {
d3.selectAll(".events")
    .style("display", timeInterval("20:00", "24:00"));    
}


//When radio button on, call updateTime function
d3.selectAll("#timeFilterRadioButton").on("change", function() {
updateTime()
});

我的问题是我无法使用 start 和 end 参数调用 timeInterval。调用timeInterval("20:00", "24:00") 会导致时间未定义。我可以成功传入数据的唯一方法是调用不带任何参数的函数:

 function updateTime(value) {
     d3.selectAll(".events")
        .style("display", timeInterval); //calling timeInterval in this manner, I'm able to console.log the time property of the data   
 }

很想知道我在哪里出错了。谢谢。

【问题讨论】:

    标签: javascript json function d3.js


    【解决方案1】:

    只需使用匿名函数来获取数据并将您的 timeInterval 函数包装在其中:

    function updateTime(value) {
        d3.selectAll(".events")
            .style("display", function(d) {
                //your datum is here---^
                return timeInterval(d, "20:00", "24:00")
                //use it here-------^
            });
    };
    

    不相关,但这个:

    if (start <= time <= end)
    

    无论end,都会为所有start &lt;= time返回true

    【讨论】:

    • 我正要写你的最后一句话,但我发现还有更多内容! ("22:00" &lt;= "23:00" &lt;= "21:00") === false 用于所有可能的字符串。第一次比较将按预期工作,产生一个布尔值,进一步评估 ltr,将与非空字符串进行比较。对于该比较,最后一个字符串将被强制转换为产生 NaN 的数字,因为冒号在内部评估为 undefined,(ecma-international.org/ecma-262/6.0/…) 为整个表达式返回 false
    • 请注意,比较数值时这有什么不同:(1 &lt;= 2 &lt;= 3) === true vs. (1 &lt;= 2 &lt;= 0) === false vs. (2 &lt;= 1 &lt;= 3) === true vs. (2 &lt;= 1 &lt;= -3) === false。就在它开始变得无聊时,你会投入一些时髦的强制!
    • @altocumulus 但是在数字方面也存在一些问题。试试(1 &lt; 3 &lt; 2),结果是true1 &lt; 3 &lt; 2 --> true &lt; 2 --> 1 &lt; 2 --> true。我的目标是向 OP 展示他们应该进行 两次 比较:if(foo &lt; bar &amp;&amp; bar &lt; baz).
    • 当然。不过,我并不是说数值比较比字符串比较更有效。我的第二条评论中的第三个表达式也不正确,至少在数学上不正确。我只是想指出 JS 中类型强制的特殊性和微妙之处。尽管该表达式在语法上是有效的,但我相信我们可以同意 (start &lt;= time &amp;&amp; time &lt;= end) 是满足 OP 需求的正确语句。
    猜你喜欢
    • 2021-05-23
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多