我有从 HTML 表创建的对象,每个对象都是该表中的一行。它们看起来像这样:
function rowObj(aName,suctionTemp,liquidTemp,outsideTemp,boxTemp,foodTemp1,foodTemp2,foodTemp3,foodTemp4,suctionPsi,liquidPsi,
compressorAmps,condensorFan,evaporatorFan,mainPower,doorSwitch,input2,input3,input4,hour,minute,amPm){
this.aName=aName,
this.suctionTemp=suctionTemp,
this.liquidTemp=liquidTemp,
this.outsideTemp=outsideTemp,
this.boxTemp=boxTemp,
this.foodTemp1=foodTemp1,
this.foodTemp2=foodTemp2,
this.foodTemp3=foodTemp3,
this.foodTemp4=foodTemp4,
this.suctionPsi=suctionPsi,
this.liquidPsi=liquidPsi,
this.compressorAmps=compressorAmps,
this.condensorFan=condensorFan,
this.evaporatorFan=evaporatorFan,
this.mainPower=mainPower,
this.doorSwitch=doorSwitch,
this.input2=input2,
this.input3=input3,
this.input4=input4,
this.hour=hour,
this.minute=minute,
this.amPm=amPm;
};
我想做的是循环这些对象并获取设备打开的时间。我可以通过以下方式做到这一点:
var minuteArray=[];
for ( var key in objects){
if (objects[key].compressorAmps > 0 && objects[key].condensorFan > 0){
minuteArray.push(objects[key].minute);
}else{
key++;
break;
}
}
var firstMinute= minuteArray.shift();
var lastMinute=minuteArray.pop();
var hourArray=[];
for ( var key in objects){
if (objects[key].compressorAmps > 0 && objects[key].condensorFan > 0){
hourArray.push(objects[key].hour);
}else{
key++;
break;
}
}
var firstHour= hourArray.shift();
var lastHour=hourArray.pop();
在这里,我将所有值插入一个数组,然后取出第一个和最后一个元素,并从中获取小时和分钟。这使我可以计算它已经运行了多长时间。这也只给我当前的运行时间。最终我想: 1. 将每组运行值存储在数组中 2.然后是数组中等于0时的值 3. 然后继续并将下一组 > 0 的位置存储在不同的数组中
for ( key in objects){
if ( objects[key].compressorAmps > 0 && objects[key].condensorFan > 0){
//store values in an array until compressorAmps === 0, skip those
//then store the next set, where compressorAmps >0 in a different array
}else if (objects[key].compressorAmps === 0 && objects[key].condensorFan === 0){
}
}
我不知道这是否可能,如果可能,我很难弄清楚。任何帮助将不胜感激。谢谢
最佳答案
将您的值放入按时间排序的数组中(我认为这就是您想要的)。然后您需要做的就是迭代数组,测试每个值并查找边缘条件。所以类似:
var result = []; // this will be a 2D array with your results
var curr = null; // this is the current run
for (var i=0; i < data.length; i++) {
if (data[i].compressorAmps > 0) { // test condition, change as needed
if (!curr) { // if we don't have a run, start one
curr = [];
}
curr.push(data[i]); // store the current value
} else {
if (curr) { // if this is the end of a run
result.push(curr); // save the run
curr = null;
}
}
}
现在您可以迭代结果
并获取每次运行的第一次和最后一次来计算时间:
for (var i=0; i < result.length; i++) {
var start = result[i][0];
var end = result[i][result[i].length - 1];
console.log("Run started at: " + start.hour + ":" start.minute);
console.log("Run ended at: " + end.hour + ":" end.minute);
}
关于javascript - 循环对象时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141909/