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

Type Casting (การแปลงชนิดข้อมูล) ใน JavaScript

Type Casting (Explicit Conversion): แปลงชนิดข้อมูลโดยเจตนารู้สึกด้วย Constructor Functions

ตัวอย่าง

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

คำอธิบาย

แปลงเป็น String

  • String(value) หรือ value.toString() หรือ '' + value

แปลงเป็น Number

  • Number(value) หรือ +value (Unary Plus) หรือ parseInt/parseFloat

แปลงเป็น Boolean

  • Boolean(value) หรือ !!value (Double Not)
  • Falsy: false, 0, -0, 0n, "", null, undefined, NaN → false

ผลลัพธ์

String = 4422 (Concatenate) | Number = 66 (Math) | Boolean = true