[英]How to loop through an array and continue at beginning once it reaches end?
我的問題:
我有一個名為“工作日”的數組:
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
假設現在是星期六,我想知道距離星期二還有多少天(顯然是 3 天)。 我怎樣才能遍歷數組 - 從“星期六”開始並從頭開始直到它到達“星期二”?
到目前為止我的代碼:
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const start = weekdays.indexOf("Sat");
const end = weekdays.indexOf("Tue");
let howManyDays = 0;
for (let i = start; i < end; i = (i + 1) % weekdays.length) {
howManyDays = howManyDays + 1;
}
但是,當我在瀏覽器的控制台中運行代碼時,“howManyDays”似乎仍然為 0。
為了使這項工作正常工作,我們需要考慮數組包裝——我在最初的回答中沒有這樣做。
所以我將在這里留下一個類似於已經存在的解決方案。
const howManyDaysBetween = (start, end) => { const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const week = weekdays.length; const startDay = weekdays.indexOf(start); const endDay = weekdays.indexOf(end); const howManyDays = startDay > endDay ? (week - startDay) + endDay : endDay - startDay; console.log(`How many days between ${start} and ${end}?: ${howManyDays}`); } howManyDaysBetween("Sat", "Tue") howManyDaysBetween("Tue", "Sat") howManyDaysBetween("Mon", "Sun") howManyDaysBetween("Fri", "Wed")
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const length = weekdays.length; // 7
const start = weekdays.indexOf("Sat"); // 5
const end = weekdays.indexOf("Tue"); // 1
let numOfDays = 0;
// If start comes after end, then we can take the difference between the start and the length,
// and add that to the end.
if (start > end) {
numOfDays = (length - start) + end;
// (7 - 5) + 1 // 3
}
// If start is before end, then just subtract one from the other.
if (start < end) {
numOfDays = end - start;
}
// If the start and end are the same, then it's 0, which is what our variable was initialised as.
return numOfDays; // 0
唯一的考慮是,您是否希望同一天為0
(如示例中所示)或7
(如果下周)。
這個循環似乎最適合提出的問題。 雖然如果你運行 2 indexOf 有點傻,但你已經獲得了距離。 只需要減去和模塊數組長度。 但是這種方法對循環很有用,因為您可以隨時比較值,直到找到“Tue”
const weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; const start = weekdays.indexOf("Sat"); const end = weekdays.indexOf("Tue"); let howManyDays = 0; for (let i = start; i != end; i++) { i = i % weekdays.length; howManyDays = howManyDays + 1; } console.log(howManyDays)
您需要計算以 7 為基數的編號系統。 以下代碼將為您簡單地完成它。
const weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; const start = weekdays.indexOf('Sat'); const end = weekdays.indexOf('Tue') + weekdays.length; const howManyDays = end - start; console.log(howManyDays);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.