gpt4 book ai didi

javascript - 返回具有给定变量 x 的两个给定时间之间等距的数组

转载 作者:行者123 更新时间:2023-11-30 11:45:34 25 4
gpt4 key购买 nike

目前我的代码如下:

 var dateArray = d3.time.scale()
.domain([new Date(2013, 1, 1), new Date(2013, 1, 7)])
.ticks(d3.time.days, 1);

在给定变量 x 的情况下,如何返回这两个日期之间间隔相等的日期数组?即 x = 10

最佳答案

从您的时间刻度中删除刻度:

var dateArray = d3.time.scale()
.domain([new Date(2013, 1, 1), new Date(2013, 1, 7)]);

并将它与您的 x 变量一起使用:

var x = 10;
var spacedDates = dateArray.ticks(x);

根据文档,ticks():

Returns representative dates from the scale's input domain. The returned tick dates are uniformly spaced (modulo irregular time intervals, such as months and leap years), have human-readable values (such as midnights), and are guaranteed to be within the extent of the input domain.

但是,数组的长度不一定是传递给 ticks 的数字:

If count is a number, then approximately count ticks will be returned. (emphasis mine)

这是一个演示:

var dateArray = d3.time.scale()
.domain([new Date(2013, 1, 1), new Date(2013, 1, 7)]);

var x = 10;
var spacedDates = dateArray.ticks(x);

console.log(spacedDates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

编辑:要获取确切 日期数,您可以使用invert() 并填充您自己的数组:

for(var i = 0; i<x; i++){
spacedDates.push(dateArray.invert(i));
}

查看演示:

var x = 10;

var dateArray = d3.time.scale()
.domain([new Date(2013, 1, 1), new Date(2013, 1, 7)])
.range([0, x-1]);

var spacedDates = [];

for(var i = 0; i<x; i++){
spacedDates.push(dateArray.invert(i));
}

console.log(spacedDates);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

关于javascript - 返回具有给定变量 x 的两个给定时间之间等距的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085866/

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