Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript Type Coercion (การแปลงชนิดข้อมูลโดยอัตโนมัติ)

Type Coercion (Implicit Conversion): JavaScript แปลงชนิดข้อมูลอัตโนมัติระหว่าง Operation

ตัวอย่าง

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Type Coercion</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>JavaScript Type Coercion</h1>
  <div class="sample">22</div>
  <div style="color: green;" class="result"></div>
  <button class="Btn">CLICK HERE</button>
  <h3> Click to add the number with 5 </h3>
  <script>
    let sampleEle = document.querySelector('.sample');
    let resEle = document.querySelector(".result");
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = ' "22" + 5 = ' + (sampleEle.innerHTML + 5);
    });
  </script>
</body>
</html>

คำอธิบาย

  • "22" + 5 → "225" (String Concatenation: Number → String)
  • "22" - 5 → 17 (Number: String → Number)
  • "22" * 2 → 44
  • == (Loose Equality) ทำ Coercion: 1 == "1" true, 0 == false true
  • === (Strict Equality) ไม่ทำ Coercion: 1 === "1" false

ตัวอย่าง Coercion ที่สับสน

[] + []      // "" (Empty String)
[] + {}      // "[object Object]"
{} + []      // 0 (Block + Unary Plus) - ใน Console
true + true  // 2
"5" - "2"    // 3
null + 1     // 1
undefined + 1 // NaN

ผลลัพธ์

แสดง: "22" + 5 = 225 (String Concatenation เพราะ + กับ String)