Javasccript(D3)-日期比较返回NaN [英] Javasccript (D3) - date comparison returns NaN
问题描述
我正在使用d3并尝试比较数组中的日期.我想要得到最小和最大.
I am using d3 and trying to compare dates in an array. I want to get the minimum and maximum of it.
以下是我的数据集.
var data = [{ "date": "2016.07.19", "close": 185697.89 }, { "date": "2016.07.20", "close": 185697.89 }, { "date": "2016.07.21", "close": 186601.1 }, { "date": "2016.07.22", "close": 187273.89 }, { "date": "2016.07.25", "close": 186807.74 }];
以下是我遇到问题的代码段
The following is the code segment I am having the issue with
max_x = 0, max_y = 0, min = 100;
for (i = 0; i < data.length; i++) {
max_y = Math.max(max_y, data[i].close);
max_x = Math.max(max_x, data[i].date);
min = Math.min(min, data[i].date);
}
当我打印"min"变量时,它打印了"NaN".
When I printed the "min" variable, it printed "NaN".
这正在影响我的其余代码.
This is affecting the rest of my code.
有人可以指出我哪里出问题了吗? 还有其他方法可以进行日期比较吗?
Can someone point out where I've gone wrong ? Is there any other way to do date comparison ?
推荐答案
您的date
值是字符串.您必须解析它们:
Your date
values are strings. You have to parse them:
var parse = d3.timeParse("%Y.%m.%d");
之后,您可以使用d3.min
检索最小值,使用d3.max
检索最大值,或者使用d3.extent
检索两者.
After that, you can retrieve the minimum with d3.min
, the maximum with d3.max
or both of them with d3.extent
.
这是演示:
var data = [{ "date": "2016.07.19", "close": 185697.89 }, { "date": "2016.07.20", "close": 185697.89 }, { "date": "2016.07.21", "close": 186601.1 }, { "date": "2016.07.22", "close": 187273.89 }, { "date": "2016.07.25", "close": 186807.74 }];
var parse = d3.timeParse("%Y.%m.%d");
var extent = d3.extent(data.map(function(d){ return parse(d.date)}))
console.log("Minimum: " + extent[0])
console.log("Maximum: " + extent[1])
<script src="https://d3js.org/d3.v4.min.js"></script>
这篇关于Javasccript(D3)-日期比较返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!