下面有一个示例数组。我想每小时检查一下,如果我在最后一分钟有一个物体,如果它不在那里,我想推一个。 例如,在下面的数组中,我们看到在02:55和03:50有一个对象,但我在00:50和01:50没有对象。那我怎么能在那些时候推动一个物体。
[{day: "2016-10-27T00:45:00.000Z", time: "00:45", val: 100}
{day: "2016-10-27T02:00:00.000Z", time: "02:00", val: 100}
{day: "2016-10-27T02:30:00.000Z", time: "02:30", val: 100}
{day: "2016-10-27T02:55:00.000Z", time: "02:55", val: 100}
{day: "2016-10-27T03:00:00.000Z", time: "03:00", val: 100}
{day: "2016-10-27T03:00:00.000Z", time: "03:00", val: 100}
{day: "2016-10-27T03:00:00.000Z", time: "03:00", val: 100}
{day: "2016-10-27T03:00:00.000Z", time: "03:00", val: 100}
{day: "2016-10-27T03:15:00.000Z", time: "03:15", val: 100}
{day: "2016-10-27T03:30:00.000Z", time: "03:30", val: 100}
{day: "2016-10-27T03:30:00.000Z", time: "03:30", val: 100}
{day: "2016-10-27T03:40:00.000Z", time: "03:40", val: 100}
{day: "2016-10-27T03:50:00.000Z", time: "03:50", val: 100}
{day: "2016-10-27T04:00:00.000Z", time: "04:00", val: 100}]
请有人帮我这个。
答案 0 :(得分:0)
将新对象添加到数组:
arr.push({day: "2016-10-27T01:00:00.000Z", time: "01:00", val: 80})
答案 1 :(得分:0)
将新对象添加到数组并在日期对其进行排序
arr.push({day: "2016-10-27T01:00:00.000Z", time: "01:00", val: 80});
arr.sort((a,b) => Date.parse(a.day)-Date.parse(b.day));
答案 2 :(得分:0)
您可以使用forEach循环:
var foundIt = false;
myArray.forEach(function(element) {
if (element.time == whatEverIWant) { // missing time
foundIt = true;
}
}
if (!foundIt) {
myArray.push({ /* insert the missing object here */ });
}
// optionally, sort the array by time
myArray.sort(function(a,b) { return a.time.localeCompare(b.time); }
如果您想为多个值执行此操作,只需使用每个值在另一个for循环中运行代码。