[英]Javascript (Typescript): for loop not working properly
我在Ionic 2中工作,並且試圖建立一個for循環以顯示某些數據。 但是它的表現很奇怪。
我目前有一個使用moment.js的“剩余時間”數組
var dur = moment.duration( moment(date).diff(moment()) );
let yearsRemain = dur.years();
let monthsRemain = dur.months();
let daysRemain = dur.days();
let hoursRemain = dur.hours();
let minutesRemain = dur.minutes();
let secondsRemain = dur.seconds();
var dateArray = [
yearsRemain,
monthsRemain,
daysRemain,
hoursRemain,
minutesRemain,
secondsRemain
]
如果我要輸出的dateArray
等this.timeString = dateArray.join(",");
並在我的html中顯示timeString
,我可以看到以下值:
0, 0, 0,-17,-46, -3 //17 hours ago
0, 0, 0, 10, 7, 47 //in 10 hours 7 minutes
0, 0, 2, 1, 9, 35 //in 2 days and 1 hour
現在,我遍歷數組,並嘗試獲得兩個最大值。 我試圖顯示一個字符串,就像我在上面的注釋中一樣。 如果是過去的話,我只想顯示最大的價值。
for(var i = 0; i < dateArray.length; i++) {
if(dateArray[i] > 0){
//If the event is in the future
this.state = "future";
this.timePrimary = dateArray[i];
this.timePrimaryType = this.typeOfTime(i, dateArray[i]);
this.timeSecondary = dateArray[i+1] !== 0 ? dateArray[i+1] : dateArray[i+2];
this.timeSecondaryType = dateArray[i+1] !== 0 ? this.typeOfTime(i+1, dateArray[i+1]) : this.typeOfTime(i+2, dateArray[i+2]);
break;
} else if(dateArray[i] < 0) {
//If the event is in the past
this.state = "past";
this.timePrimary = dateArray[i] * (-1);
this.timePrimaryType = this.typeOfTime(i, (dateArray[i] * (-1))) + " ago";
break;
} else {
i++
}
}
此循環遍歷每個數組項,並且應捕獲不為0
的第一個數組項。 如果它大於0,則該事件將在將來發生,並且我想捕獲該數字和下一個(如果下一個為零,請找到下一個,我將很快升級此部分)。
這是問題
出於某種原因,它跳過hours
的陣列的一部分,當小時數最多。 從上面舉第二個例子: 0, 0, 0, 10, 7, 47
。 我所看到的是7 minutes and 47 seconds
,應該讀10 hours and 7 minutes
。
有什么想法為什么會這樣?
萬一您想問問,這里是typeOfType
函數:
typeOfTime(type, num) {
var display;
var plur = num === 1 ? "" : "s";
switch(type) {
case 0:
display = "Year" + plur;
break;
case 1:
display = "Month" + plur;
break;
case 2:
display = "Day" + plur;
break;
case 3:
display = "Hour" + plur;
break;
case 4:
display = "Minute" + plur;
break;
case 5:
display = "Second" + plur;
break;
}
return display;
}
這是因為代碼中的else
語句正在使計數器i
遞增,並且導致循環在到達0
時跳過數組中的下一項。 這就是為什么在0
之后跳過10
原因。 刪除該部分,它應該可以工作。
for(var i = 0; i < dateArray.length; i++) {
if(dateArray[i] > 0){
//If the event is in the future
this.state = "future";
this.timePrimary = dateArray[i];
this.timePrimaryType = this.typeOfTime(i, dateArray[i]);
this.timeSecondary = dateArray[i+1] !== 0 ? dateArray[i+1] : dateArray[i+2];
this.timeSecondaryType = dateArray[i+1] !== 0 ? this.typeOfTime(i+1, dateArray[i+1]) : this.typeOfTime(i+2, dateArray[i+2]);
break;
} else if(dateArray[i] < 0) {
//If the event is in the past
this.state = "past";
this.timePrimary = dateArray[i] * (-1);
this.timePrimaryType = this.typeOfTime(i, (dateArray[i] * (-1))) + " ago";
break;
} else {
//do nothing... let the loop to go on.
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.