JavaScript
Built-in Classes
Math
เรียนรู้ `Math` built-in object — static methods สำหรับปัดเศษ, สุ่มเลข, หาค่ามากสุด/น้อยสุด, ยกกำลัง, รากที่สอง, ค่าสัมบูรณ์ และค่าคงที่ทางคณิตศาสตร์ที่ใช้บ่อยในงานคำนวณ
`Math` คือ built-in object สำหรับคำนวณ — ใช้ static methods โดยตรง ไม่ต้องสร้าง instance
`Math` เป็น built-in object ใน JavaScript — เป็น object ระดับ global ที่เก็บ **static properties** (ค่าคงที่เช่น `Math.PI`) และ **static methods** (ฟังก์ชันเช่น `Math.round()`, `Math.random()`) ไว้ให้เรียกใช้ได้ทันที `Math` **ต่างจาก** `Number`, `String`, `Date` ที่เรียนไปแล้วตรงจุดสำคัญ: - `Number`, `String`, `Date` — เป็น **constructor** — สร้าง instance ด้วย `new` ได้ - `Math` — เป็น **namespace object** — ไม่ใช่ constructor — **ใช้ `new Math()` ไม่ได้** ทุกอย่างใน `Math` เรียกผ่าน `Math.` โดยตรง: ```js Math.round(3.7); // 4 Math.PI; // 3.141592653589793 Math.random(); // 0.473829... ``` `Math` คล้ายตอนที่เราใช้ static methods ของ `Number` (`Number.isInteger()`, `Number.isNaN()`) — ไม่ต้องสร้าง instance ก็เรียกใช้ได้เลย **Use case หลักของ Math**: ปัดเศษ (round/ceil/floor), สุ่มเลข (random), หาค่ามากสุด/น้อยสุด (min/max), ยกกำลัง (pow), รากที่สอง (sqrt), ค่าสัมบูรณ์ (abs), และค่าคงที่ (PI, E)
// Math ไม่ใช่ constructor — ใช้ new ไม่ได้
// const m = new Math(); // ❌ TypeError: Math is not a constructor
// ใช้ Math. เรียก static method ได้โดยตรง
console.log(Math.round(3.7)); // 4
console.log(Math.floor(4.9)); // 4
console.log(Math.random()); // 0.xxx (สุ่มทุกครั้ง)
// static properties — ค่าคงที่
console.log(Math.PI); // 3.141592653589793
console.log(Math.E); // 2.718281828459045- `Math` เป็น namespace object — ไม่ใช่ constructor — `new Math()` ใช้ไม่ได้
- ทุก method และ property ใน `Math` เป็น static — เรียกผ่าน `Math.` โดยตรง
- `Math` ต่างจาก `Number`/`String`/`Date` ที่สร้าง instance ได้ — `Math` ไม่ต้องสร้างก็ใช้ได้
- วิธีเรียกเหมือน `Number.isInteger()` ที่เรียนไปแล้ว — ผ่านชื่อ class โดยตรง
- method ทุกตัวใน `Math` คืนค่าเป็นตัวเลข — ไม่เปลี่ยนค่าของ instance (เพราะไม่มี instance ให้เปลี่ยน)
ปัดเศษ — `Math.round()`, `Math.ceil()`, `Math.floor()`, `Math.trunc()`
`Math` มี method ปัดเศษ 4 ตัว — แต่ละตัวมีพฤติกรรมต่างกัน: **`Math.round(x)`** — ปัดตามหลักคณิตศาสตร์ — `.5` ขึ้น, ต่ำกว่า `.5` ลง: - `Math.round(3.4)` → `3` - `Math.round(3.5)` → `4` (ปัดขึ้นเมื่อ .5) - `Math.round(-3.5)` → `-3` (ปัดขึ้นเช่นกัน — -3 มากกว่า -4) **`Math.ceil(x)`** — ปัดขึ้นเสมอ (ceiling = เพดาน): - `Math.ceil(3.1)` → `4` - `Math.ceil(-3.1)` → `-3` (ขึ้น = เข้าใกล้ 0 มากขึ้น เพราะเป็นค่าลบ) **`Math.floor(x)`** — ปัดลงเสมอ (floor = พื้น): - `Math.floor(3.9)` → `3` - `Math.floor(-3.9)` → `-4` (ลง = ห่างจาก 0 มากขึ้น เพราะเป็นค่าลบ) **`Math.trunc(x)`** — ตัดทศนิยมทิ้ง (truncate) — ไม่สนว่าจะเป็นบวกหรือลบ: - `Math.trunc(3.9)` → `3` - `Math.trunc(-3.9)` → `-3` **ความแตกต่างสำคัญระหว่าง floor กับ trunc อยู่ที่ค่าลบ**: - `Math.floor(-3.1)` → `-4` - `Math.trunc(-3.1)` → `-3`
const nums = [3.4, 3.5, 3.9, -3.4, -3.5, -3.9];
for (const n of nums) {
console.log(`n=${n}`);
console.log(` round: ${Math.round(n)}`);
console.log(` ceil: ${Math.ceil(n)}`);
console.log(` floor: ${Math.floor(n)}`);
console.log(` trunc: ${Math.trunc(n)}`);
}
// output:
// n=3.4 round:3 ceil:4 floor:3 trunc:3
// n=3.5 round:4 ceil:4 floor:3 trunc:3
// n=3.9 round:4 ceil:4 floor:3 trunc:3
// n=-3.4 round:-3 ceil:-3 floor:-4 trunc:-3
// n=-3.5 round:-3 ceil:-3 floor:-4 trunc:-3
// n=-3.9 round:-4 ceil:-3 floor:-4 trunc:-3| method | 3.4 | 3.5 | 3.9 | -3.4 | -3.5 | -3.9 | หลักการ |
|---|---|---|---|---|---|---|---|
| `Math.round()` | 3 | 4 | 4 | -3 | -3 | -4 | ปัด .5 ขึ้น — ไปหาค่าใกล้สุด |
| `Math.ceil()` | 4 | 4 | 4 | -3 | -3 | -3 | ปัดขึ้นเสมอ — ceiling = เพดาน |
| `Math.floor()` | 3 | 3 | 3 | -4 | -4 | -4 | ปัดลงเสมอ — floor = พื้น |
| `Math.trunc()` | 3 | 3 | 3 | -3 | -3 | -3 | ตัดทศนิยมทิ้ง — ไม่สนเครื่องหมาย |
- `Math.round()` ปัดตามหลักคณิตศาสตร์ — .5 ขึ้น — ใช้บ่อยที่สุดในชีวิตประจำวัน
- `Math.floor()` ใช้บ่อยกับการสุ่มเลข — `Math.floor(Math.random() * N)` — เรียนในหัวข้อต่อไป
- `Math.ceil()` ใช้เมื่อต้องการ 'อย่างน้อยเท่านี้' — เช่น คำนวณจำนวนหน้าที่ต้องใช้เมื่อแต่ละหน้าใส่ของได้ไม่เกิน N ชิ้น
- `Math.trunc()` ใช้เมื่อต้องการตัดทศนิยมทิ้งโดยไม่สนเครื่องหมาย — พฤติกรรมตรงไปตรงมาที่สุด
- **กับดัก**: ค่าลบ — `floor(-3.1) = -4` ไม่ใช่ `-3` — ถ้าต้องการแค่ 'เอาจำนวนเต็ม' ให้ใช้ `trunc`
`Math.min()` และ `Math.max()` — หาค่าน้อยสุดและมากสุด
`Math.min(a, b, c, ...)` คืนค่าที่น้อยที่สุดจาก argument ที่ส่งเข้าไป `Math.max(a, b, c, ...)` คืนค่าที่มากที่สุด **รับ argument ได้หลายตัว** — คั่นด้วยเครื่องหมาย `,` ```js Math.min(5, 2, 9, 1, 7); // 1 Math.max(5, 2, 9, 1, 7); // 9 ``` **ใช้กับ array ผ่าน spread operator**: ```js const scores = [78, 92, 65, 88]; Math.max(...scores); // 92 Math.min(...scores); // 65 ``` **Edge case**: - `Math.min()` — ไม่ส่ง argument เลย → `Infinity` (ค่ามากสุดที่เป็นไปได้ = ทุกอย่างน้อยกว่า Infinity) - `Math.max()` — ไม่ส่ง argument เลย → `-Infinity` - ถ้ามี `NaN` ใน argument → ผลลัพธ์เป็น `NaN`
// ส่ง argument หลายตัว
console.log(Math.max(5, 2, 9, 1)); // 9
console.log(Math.min(5, 2, 9, 1)); // 1
// ใช้กับ array ผ่าน spread
const prices = [299, 599, 149, 899, 49];
console.log("สูงสุด:", Math.max(...prices)); // 899
console.log("ต่ำสุด:", Math.min(...prices)); // 49
// edge cases
console.log(Math.max()); // -Infinity
console.log(Math.min()); // Infinity
console.log(Math.max(1, NaN, 3)); // NaN- `Math.min()` / `Math.max()` รับ argument ได้หลายตัว — ไม่ต้องใช้ array
- ใช้ spread `...` เพื่อส่ง array เป็น argument แต่ละตัว — `Math.max(...arr)`
- `Math.min()` เปล่า → `Infinity`, `Math.max()` เปล่า → `-Infinity` — แปลว่า 'ไม่มีค่าอะไรให้น้อย/มากกว่า'
- ถ้ามี `NaN` ใน argument → ผลลัพธ์เป็น `NaN` — ต้องกรอง `NaN` ออกก่อนใช้
- ใช้ `Math.max()` เพื่อหาคะแนนสูงสุด, ราคาแพงสุด, หรืออุณหภูมิสูงสุดในชุดข้อมูล
`Math.random()` — สุ่มเลข 0 ถึงน้อยกว่า 1 และการสร้างช่วงที่ต้องการ
`Math.random()` คืนค่า **ทศนิยมสุ่ม** ระหว่าง `0` (รวม) ถึงน้อยกว่า `1` (ไม่รวม) — ทุกครั้งที่เรียกจะได้ค่าใหม่ ```js Math.random(); // 0.473829... Math.random(); // 0.882156... Math.random(); // 0.091234... ``` **ค่าที่ได้อยู่ในช่วง `[0, 1)`** — คือ 0 ≤ result < 1 การใช้งานจริงเรามักต้องการสุ่มเป็นจำนวนเต็มในช่วงที่กำหนด — ใช้สูตร: **สุ่มจำนวนเต็มในช่วง `[min, max]`** (รวม min และ max): ```js Math.floor(Math.random() * (max - min + 1)) + min ``` ตัวอย่าง: - สุ่มเลข 1–6 (ลูกเต๋า): `Math.floor(Math.random() * 6) + 1` - สุ่มเลข 0–99: `Math.floor(Math.random() * 100)` - สุ่มเลข 10–20: `Math.floor(Math.random() * 11) + 10` **ทำไมต้องใช้ `Math.floor`**: `Math.random()` คืนทศนิยม — เราคูณเพื่อขยายช่วง แล้วปัดลงด้วย `Math.floor` เพื่อให้ได้จำนวนเต็มที่อยู่ในช่วงพอดี **ข้อควรรู้**: `Math.random()` ไม่ใช่ random แบบ cryptographic — ไม่ควรใช้สร้าง password หรือ token!
// Math.random() — ค่าดิบ 0 ถึงน้อยกว่า 1
console.log(Math.random()); // 0.4738... (เปลี่ยนทุกครั้ง)
console.log(Math.random()); // 0.8821...
// สุ่มลูกเต๋า 1-6 — สูตร: Math.floor(Math.random() * 6) + 1
const dice = Math.floor(Math.random() * 6) + 1;
console.log("ลูกเต๋า:", dice);
// สุ่มเลข 0-99 — สูตร: Math.floor(Math.random() * 100)
const score = Math.floor(Math.random() * 100);
console.log("คะแนนสุ่ม:", score);
// สุ่มเลขในช่วง [10, 20]
const between = Math.floor(Math.random() * 11) + 10;
console.log("เลข 10-20:", between);
// ทดลองสุ่ม 10 ครั้งดูการกระจาย
for (let i = 0; i < 10; i++) {
console.log(Math.floor(Math.random() * 6) + 1);
}| ช่วงที่ต้องการ | สูตร | ตัวอย่าง |
|---|---|---|
| `[0, 1)` — ค่าดิบ | `Math.random()` | `0.47382...` |
| `[0, N)` — 0 ถึง N-1 | `Math.floor(Math.random() * N)` | สุ่ม 0–99: `* 100` |
| `[1, N]` — 1 ถึง N | `Math.floor(Math.random() * N) + 1` | ลูกเต๋า: `* 6 + 1` |
| `[min, max]` | `Math.floor(Math.random() * (max - min + 1)) + min` | 10–20: `* 11 + 10` |
- `Math.random()` คืนค่า `0 ≤ result < 1` — 0 รวม, 1 ไม่รวม
- ใช้ `Math.floor(Math.random() * range) + min` เพื่อสุ่มในช่วงที่ต้องการ
- **จำให้ขึ้นใจ**: สุ่ม 1–6 → `Math.floor(Math.random() * 6) + 1` — ไม่ใช่ `* 5 + 1` (จะได้แค่ 1–5)
- `Math.random()` ไม่เหมาะกับ security — ใช้ `crypto.getRandomValues()` เมื่อต้องการ random ที่ปลอดภัย
- ใช้ `Math.random()` กับ `Math.floor()` เพื่อเลือกสมาชิกสุ่มจาก array: `arr[Math.floor(Math.random() * arr.length)]`
`Math.abs()`, `Math.sign()`, `Math.pow()`, `Math.sqrt()` — เครื่องมือคำนวณที่ใช้บ่อย
นอกจากปัดเศษและสุ่มเลขแล้ว `Math` ยังมี method พื้นฐานที่มีประโยชน์อีกหลายตัว: **`Math.abs(x)`** — **absolute value** — คืนค่าระยะห่างจาก `0` (ค่าบวกเสมอ): - `Math.abs(-5)` → `5` - `Math.abs(5)` → `5` - ใช้หาผลต่างโดยไม่สนทิศทาง เช่น `Math.abs(a - b)` = ระยะห่างระหว่าง a กับ b **`Math.sign(x)`** — คืน **เครื่องหมาย** ของตัวเลข: - `Math.sign(-42)` → `-1` - `Math.sign(0)` → `0` - `Math.sign(42)` → `1` - `Math.sign(-0)` → `-0`, `Math.sign(NaN)` → `NaN` **`Math.pow(base, exponent)`** — **ยกกำลัง**: - `Math.pow(2, 3)` → `8` (2³) - `Math.pow(5, 2)` → `25` (5²) - ใช้ `**` operator ได้เช่นกัน: `2 ** 3` → `8` **`Math.sqrt(x)`** — **รากที่สอง** (square root): - `Math.sqrt(9)` → `3` - `Math.sqrt(2)` → `1.4142135623730951` - `Math.sqrt(-1)` → `NaN` (รากที่สองของค่าลบไม่มีในจำนวนจริง)
// === Math.abs — ระยะห่างจาก 0 ===
console.log(Math.abs(-5)); // 5
console.log(Math.abs(5)); // 5
console.log(Math.abs(-3.14)); // 3.14
// ใช้หาผลต่างแบบไม่สนทิศทาง
const diff = Math.abs(10 - 7); // 3 (ระยะห่างระหว่าง 10 กับ 7)
console.log(diff);
// === Math.sign — เครื่องหมาย ===
console.log(Math.sign(-42)); // -1
console.log(Math.sign(0)); // 0
console.log(Math.sign(42)); // 1
// === Math.pow — ยกกำลัง ===
console.log(Math.pow(2, 3)); // 8 (2³)
console.log(Math.pow(10, 2)); // 100 (10²)
console.log(Math.pow(3, 4)); // 81 (3⁴)
console.log(2 ** 3); // 8 (ใช้ ** ได้ผลเหมือนกัน)
// === Math.sqrt — รากที่สอง ===
console.log(Math.sqrt(9)); // 3
console.log(Math.sqrt(25)); // 5
console.log(Math.sqrt(2)); // 1.4142135623730951
console.log(Math.sqrt(-1)); // NaN| method | ใช้เมื่อไหร่ | ตัวอย่าง |
|---|---|---|
| `Math.abs(x)` | ต้องการระยะห่างหรือผลต่างแบบไม่สนทิศทาง | `Math.abs(price1 - price2)` หาส่วนต่างราคา |
| `Math.sign(x)` | เช็กว่าเลขเป็นบวก ลบ หรือศูนย์ | ตรวจสอบทิศทางในเกม |
| `Math.pow(b, e)` | ยกกำลัง — b^e | คำนวณดอกเบี้ยทบต้น, พื้นที่ |
| `Math.sqrt(x)` | รากที่สอง — √x | คำนวณด้านจากพื้นที่, ระยะห่าง |
- `Math.abs()` มีประโยชน์มากในการหาผลต่าง — `Math.abs(a - b)` = ระยะห่างโดยไม่สนว่าค่าไหนมาก่อน
- `Math.sign()` คืน `-1`, `0`, `1` — ใช้แยกประเภทค่าหรือตัดสินใจตามเครื่องหมาย
- `Math.pow()` กับ `**` operator ให้ผลลัพธ์เหมือนกัน — ใช้ `**` สั้นกว่า: `2 ** 10` = 1024
- `Math.sqrt()` ต้องการค่าที่ไม่ติดลบ — ถ้าติดลบจะได้ `NaN`
- method ทั้งหมดคืนค่าเป็น number — ไม่เปลี่ยนค่าอะไร (ไม่มี instance ให้เปลี่ยน)
ค่าคงที่ทางคณิตศาสตร์ — `Math.PI`, `Math.E` และอื่น ๆ
`Math` มี static properties ที่เป็นค่าคงที่ทางคณิตศาสตร์ — ค่าเหล่านี้เป็น **read-only** — เปลี่ยนไม่ได้ **`Math.PI`** — ค่า π ≈ 3.141592653589793 — ใช้มากที่สุด: - เส้นรอบวงกลม: `2 * Math.PI * radius` - พื้นที่วงกลม: `Math.PI * radius * radius` - เรเดียน: `degrees * Math.PI / 180` **`Math.E`** — Euler's number ≈ 2.718281828459045 — ฐานของ natural logarithm: - ใช้ใน `Math.exp(x)` = e^x - ใช้ใน `Math.log(x)` = ln(x) **ค่าคงที่อื่นที่มีใน Math**: - `Math.LN2` — ln(2) ≈ 0.693 - `Math.LN10` — ln(10) ≈ 2.303 - `Math.LOG2E` — log₂(e) ≈ 1.443 - `Math.LOG10E` — log₁₀(e) ≈ 0.434 - `Math.SQRT2` — √2 ≈ 1.414 - `Math.SQRT1_2` — √½ ≈ 0.707 ในทางปฏิบัติ คุณจะใช้ `Math.PI` บ่อยที่สุด — ค่าอื่น ๆ มักใช้ในงานคณิตศาสตร์เฉพาะทาง
// === ใช้ Math.PI คำนวณวงกลม ===
const radius = 5;
// พื้นที่วงกลม: πr²
const area = Math.PI * Math.pow(radius, 2);
console.log("พื้นที่:", area);
// พื้นที่: 78.53981633974483
// เส้นรอบวง: 2πr
const circumference = 2 * Math.PI * radius;
console.log("เส้นรอบวง:", circumference);
// เส้นรอบวง: 31.41592653589793
// === แปลงองศาเป็นเรเดียน ===
const degrees = 180;
const radians = degrees * (Math.PI / 180);
console.log("180° =", radians, "rad");
// 180° = 3.141592653589793 rad (= π)
// === Math.E ===
console.log(Math.E); // 2.718281828459045
console.log(Math.exp(1)); // 2.718281828459045 (= e¹)
console.log(Math.log(Math.E)); // 1 (= ln(e))
// ค่าคงที่เปลี่ยนไม่ได้
// Math.PI = 3; // ❌ ไม่ error แต่ก็ไม่ได้เปลี่ยน| ค่าคงที่ | ค่าประมาณ | ใช้ใน |
|---|---|---|
| `Math.PI` | 3.14159 | วงกลม, เรเดียน, ตรีโกณมิติ |
| `Math.E` | 2.71828 | `Math.exp()`, `Math.log()`, ดอกเบี้ยทบต้น |
| `Math.SQRT2` | 1.41421 | เรขาคณิต, ระยะห่าง, normalize |
| `Math.LN2` | 0.69315 | logarithm ฐาน 2 |
| `Math.LN10` | 2.30259 | logarithm ฐาน 10 |
- `Math.PI` เป็นค่าคงที่ที่ใช้บ่อยที่สุด — จำสูตร `Math.PI * r * r` (พื้นที่) และ `2 * Math.PI * r` (เส้นรอบวง)
- ค่าคงที่ของ `Math` เป็น read-only — เปลี่ยนไม่ได้ (strict mode จะ throw error)
- `Math.PI / 180` ใช้แปลงองศาเป็นเรเดียน — จำเป็นเมื่อใช้ `Math.sin()`, `Math.cos()` เพราะรับค่าเป็นเรเดียน
- `Math.E` ใช้คู่กับ `Math.exp()` และ `Math.log()` — ในงานคำนวณการเติบโต, ดอกเบี้ย, สถิติ