如何在 JavaScript 中使用 map 函式來判斷時間是否處於特定時間範圍內?


假設我們的科目記錄計劃的學習時間如下 −

const scheduleDetails = [
   { subjectName: 'JavaScript', studyTime: '5 PM - 11 PM' },
   { subjectName: 'MySQL', studyTime: '12 AM - 4PM' }
]

我們可以使用 map() 函式。以下是程式碼 −

示例

const scheduleDetails = [
   { subjectName: 'JavaScript', studyTime: '5 PM - 11 PM' },
   { subjectName: 'MySQL', studyTime: '12 AM - 4PM' }
]
function timeToReadSubjectName(scheduleDetails) {
   var currentTime = new Date().getHours();
   let result = '';
   scheduleDetails.map(obj => {
      const hourDetails = obj.studyTime.split(' ');
      const firstCurrentTime = hourDetails[1] === 'PM' ? 12 : 0;
      const secondCurrentTime = hourDetails[4] === 'PM' ? 12 : 0;
      if (currentTime > (+hourDetails[0] + firstCurrentTime) &&
      currentTime < (+hourDetails[3] + secondCurrentTime)) {
         result = obj.subjectName;
      };
   })
   return result;
}
console.log("The Subject which you need to read in this
time="+timeToReadSubjectName(scheduleDetails));

要執行上面的程式,你需要使用以下命令 −

node fileName.js.

我的檔名是 demo128.js。

輸出

這將生成以下輸出 −

PS C:\Users\Amit\JavaScript-code> node demo128.js
The Subject which you need to read in this time=JavaScript

更新日期:10-Sep-2020

171 次瀏覽

啟動你的職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.