gpt4 book ai didi

javascript - D3.js - 日期字符串比较失败(未找到最小和最大日期)

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

我想比较一组日期字符串以获得它的最大值和最小值。以下是我的数据集。

  var data=[{ "date": "2016.07.28", "close": 186889.45 }, { "date": 
"2016.07.29", "close": 187156.54 }, { "date": "2016.08.01", "close":
187218.54 }, { "date": "2016.08.02", "close": 187624.73 }];

这就是我比较它们的方式。

         var parseTime = d3.time.format("%Y.%m.%d").parse;

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, parseTime (data[i].date));
min = Math.min(min, parseTime (data[i].date));
}

日期比较似乎没有发生。这不是在 javascript 中比较日期字符串的方式吗?

我使用的是 d3 版本 3。

最佳答案

问题出在这里:

min = Math.min(min, parseTime (data[i].date));
max_x = Math.max(max_x, parseTime(data[i].date));

您正在使用 Math.maxMath.min 来比较一个日期和一个数字,并且因此,您将获得时间戳中的日期。

查看代码的输出:

var data = [{
"date": "2016.07.28",
"close": 186889.45
}, {
"date": "2016.07.29",
"close": 187156.54
}, {
"date": "2016.08.01",
"close": 187218.54
}, {
"date": "2016.08.02",
"close": 187624.73
}];

var parseTime = d3.time.format("%Y.%m.%d").parse;

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, parseTime(data[i].date));
min = Math.min(min, parseTime(data[i].date));
}

console.log("Max is " + max_x)
console.log("Min is " + min)
<script src="https://d3js.org/d3.v3.min.js"></script>

根据 ECMA Documentation , Math.maxMath.min:

Given zero or more arguments, calls ToNumber on each of the arguments and returns the smallest of the resulting values.

  • If no arguments are given, the result is +∞.
  • If any value is NaN, the result is NaN.
  • The comparison of values to determine the smallest value is done using the Abstract Relational Comparison algorithm (7.2.11) except that +0 is considered to be larger than −0.

解决方法:

改用d3.mind3.max

这是演示:

var data = [{
"date": "2016.07.28",
"close": 186889.45
}, {
"date": "2016.07.29",
"close": 187156.54
}, {
"date": "2016.08.01",
"close": 187218.54
}, {
"date": "2016.08.02",
"close": 187624.73
}];

var parseTime = d3.time.format("%Y.%m.%d").parse;

var max = d3.max(data, function(d){ return parseTime(d.date)})
var min = d3.min(data, function(d){ return parseTime(d.date)})

console.log("Max is: " + max)
console.log("Min is: " + min)
<script src="https://d3js.org/d3.v3.min.js"></script>

关于javascript - D3.js - 日期字符串比较失败(未找到最小和最大日期),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45228574/

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