Giả sử, chúng tôi có hồ sơ chủ đề với thời gian chúng tôi dự định nghiên cứu chúng -
const scheduleDetails = [
{ subjectName: 'JavaScript', studyTime: '5 PM - 11 PM' },
{ subjectName: 'MySQL', studyTime: '12 AM - 4PM' }
] Đây là cách chúng ta có thể sử dụng map (). Sau đây là mã -
Ví dụ
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)); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo128.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo128.js The Subject which you need to read in this time=JavaScript