gpt4 book ai didi

javascript - 如何使用 javascript/jquery 从数组中获取最大和最小日期?

转载 作者:行者123 更新时间:2023-11-29 16:47:04 25 4
gpt4 key购买 nike

我想从一个 json 数组中获取最小和最大日期:

我的代码

$.getJSON(url, function (data) {
var dates = Object.keys( data['data']['horodate'] ).map(function ( key ) {
return data['data']['horodate'][key].replace(/\-/g,'/' )
});
var min = new Date(Math.min.apply( null, dates ));
var max = new Date(Math.max.apply( null, dates));
});

data 数组是:

Array [ 
"2016/10/13 00:00:00",
"2016/10/13 00:30:00",
"2016/10/13 01:00:00",
"2016/10/13 01:30:00",
"2016/10/13 02:00:00",
"2016/10/13 02:30:00",
"2016/10/13 03:00:00",
"2016/10/13 03:30:00",
"2016/10/13 04:00:00",
"2016/10/13 04:30:00"
]

但我有一个错误:无效日期。你能帮帮我吗?

最佳答案

使用 Array#sort 使用自定义排序功能并获取最后(最大)和第一个(最小)值。

data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];

var sorted = data.slice() // copy the array for keeping original array with order
// sort by parsing them to date
.sort(function(a, b) {
return new Date(a) - new Date(b);
});

// get the first and last values
console.log(
'max :', sorted.pop(), 'min :', sorted.shift()
);


或者用一个简单的 Array#forEach 循环。

data = ["2016/10/13 00:00:00", "2016/10/13 00:30:00", "2016/10/13 01:00:00", "2016/10/13 01:30:00", "2016/10/13 02:00:00", "2016/10/13 02:30:00", "2016/10/13 03:00:00", "2016/10/13 03:30:00", "2016/10/13 04:00:00", "2016/10/13 04:30:00"];

// initially set max and min as first element
var max = data[0],
min = data[0];

// iterate over array values and update min & max
data.forEach(function(v) {
max = new Date(v) > new Date(max)? v: max;
min = new Date(v) < new Date(min)? v: min;
});

console.log('max :', max, 'min :', min);

关于javascript - 如何使用 javascript/jquery 从数组中获取最大和最小日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40018503/

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