JavaScript 內建了許多現成的物件與方法,不必自己從頭寫。本篇整理最常用的五類:日期(Date)、數學(Math)、字串、陣列與 JSON。熟悉它們,可以省下大量重複的程式碼。
一、Date:日期與時間
const now = new Date(); // 現在的日期時間
console.log(now.getFullYear()); // 年,例如 2026
console.log(now.getMonth() + 1); // 月:回傳 0~11,所以要加 1
console.log(now.getDate()); // 日
console.log(now.getDay()); // 星期:0 是星期日,6 是星期六
console.log(now.toLocaleDateString('zh-TW')); // 依地區格式顯示日期
最容易出錯的是月份:getMonth() 的 0 代表一月。建立指定日期時也是同樣規則:
const newYear = new Date(2027, 0, 1); // 2027 年 1 月 1 日(月份寫 0)
計算兩個日期相差幾天
const d1 = new Date(2026, 10, 8); // 2026-11-08
const d2 = new Date(2027, 0, 1); // 2027-01-01
const days = Math.round((d2 - d1) / (1000 * 60 * 60 * 24));
console.log(days); // 54
兩個日期相減,得到的是毫秒數,再除以一天的毫秒數即可。使用 Math.round 是為了避開夏令時間造成的小誤差。
二、Math:數學運算
| 方法 | 說明 | 範例 |
Math.round(x) | 四捨五入 | Math.round(2.5) 得 3 |
Math.floor(x) | 無條件捨去 | Math.floor(2.9) 得 2 |
Math.ceil(x) | 無條件進位 | Math.ceil(2.1) 得 3 |
Math.max/min | 最大/最小值 | Math.max(3, 9, 5) 得 9 |
Math.random() | 0 到不含 1 的隨機小數 | 見下方 |
// 擲骰子:1~6 的隨機整數
const dice = Math.floor(Math.random() * 6) + 1;
// 陣列取最大值,用展開運算子
const scores = [78, 92, 65];
console.log(Math.max(...scores)); // 92
另外,(3.14159).toFixed(2) 可以指定小數位數,回傳的是字串 '3.14';(1234567).toLocaleString('zh-TW') 會加上千分位,得到 '1,234,567'。