Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Lấy thế kỷ từ năm trong JavaScript


Chúng ta cần viết hàm nhận số hoặc chuỗi đại diện năm. Từ năm đó hàm xác định và trả về thế kỷ năm đó rơi vào.

Ví dụ - f("2000") = 20, f(1999) = 20, f("2002") = 21.

Ví dụ

Code sau đây:

const centuryFromYear = year => { 
  if (typeof year == 'string') { 
    if (year.toString().slice(-2) == '00') return year.toString().slice(0, 2); 
    else return (Math.floor(+year / 100) + 1).toString(); 
  } else if (typeof year == 'number') { 
    return Math.floor((year - 1) / 100) + 1; 
  } else { 
    return undefined; 
  } 
}; 
console.log(centuryFromYear("2000")); 
console.log(centuryFromYear("2002")); 
console.log(centuryFromYear(1999));

Kết quả

Kết quả trên console:

20 21 20