javascript - 映射到 d3 中的序数刻度时如何计算闰年?

标签 javascript d3.js

当我将我的日期映射到我的 x.domain() 比例时,我错过了闰年日期“02-29”。我尝试使用这种方法添加它:

x.domain(data.map(function(d) { return d.xPos, "02-29"; }));

但它只是将它添加到数组的末尾。另一种方法是重新排列 CSV 文件并将闰年放在首位。这行得通,但看起来很老套。所以我想按如下方式添加它但卡住了:

    // define the x-scale 'manually' using a leap year
        var mindate = new Date(2016,0,1),
            maxdate = new Date(2016,11,31);

   // I then need to set the x.domain but the problem is I want it to be an Ordinal scale
       var x = d3.time.scale()
            .domain([mindate, maxdate]) 

当我正确设置 x.domain() 后,我会遇到缩放非闰年的问题。如何为没有 2 月 29 日值的年份添加条件,以便为“02-29”x 值赋予相应的 0 作为 y 值?

你可以看到我的blockbuilder here或者我的 block.ck here .请注意右侧 2016 年的 02-29 条。

最佳答案

尝试不同的方法,已经有一些函数可以帮助你得到闰年。如:

函数闰年(年){ 返回 ((年 % 4 == 0) && (年 % 100 != 0)) || (年 % 400 == 0); }

然后获取返回值并使用 if 语句更改 maxdate 的值

if (leapYear(maxdate[0]) && maxdate[1] == 2 && maxdate[2] == 28){ maxdate = new Date(年, 2 , 29) }别的{ /* 照常工作 */ }

关于javascript - 映射到 d3 中的序数刻度时如何计算闰年?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36581894/

相关文章:

javascript - 无法将 id 值分配给 html 输入标记

javascript - 在 JavaScript 中对带有参数的函数使用 setInterval()

javascript - D3.js如何获取transform attr的值

javascript - 如何在 donut chart 中间加一个圆圈并在d3 js中填充?

javascript - 为什么当我 console.log 我的 promise 时返回整数值

javascript - 如何使用数组中的每个?

rMaps ichoropleth 与自定义 map /shp

d3.js - d3 对数刻度不显示

javascript - Cufon,cufontext 在 jQuery 克隆 IE7 上中断

html - 如何增加 d3.js 中的 slider 长度