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

Ép kiểu (Type Casting) trong JavaScript

Type Casting (Ép kiểu tường minh) là chuyển đổi chủ động từ kiểu dữ liệu này sang kiểu khác bằng các hàm constructor: String(), Number(), Boolean().

Khác với Type Coercion (Ép kiểu ngầm) - JavaScript tự động chuyển kiểu.

Các hàm chuyển đổi chính:

HàmChuyển thànhVí dụKết quả
String()StringString(123)"123"
Number()NumberNumber("123")123
Boolean()BooleanBoolean(1)true
BigInt()BigIntBigInt(123)123n

Phương thức object:

// Object → String
obj.toString();
String(obj);

// Object → Number (valueOf -> toString)
Number(obj);
+obj; // Unary plus

Ví dụ minh họa

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Type Casting JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
    .sample { font-size: 20px; font-weight: 500; margin: 10px 0; font-family: monospace; }
    .result { font-size: 18px; font-weight: 500; margin: 10px 0; color: green; }
    button { padding: 8px 16px; cursor: pointer; }
    table { border-collapse: collapse; width: 100%; margin-top: 20px; }
    th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
    th { background: #f5f5f5; }
  </style>
</head>
<body>
  <h1>Type Casting (Ép kiểu tường minh) trong JavaScript</h1>
  <div class="sample" id="sample">44</div>
  <div class="result" id="result"></div>
  <button class="Btn" id="btn">CHUYỂN ĐỔI</button>
  <h3> Nhấn nút để chuyển giá trị thành String, Number, Boolean </h3>
  <script>
    const sampleEle = document.querySelector('#sample');
    const resEle = document.querySelector("#result");
    
    document.querySelector("#btn").addEventListener("click", () => {
      const input = sampleEle.innerHTML; // "44" (string)
      const num = Number(input); // 44 (number)
      
      resEle.innerHTML = `
        Input: "${input}" (${typeof input})

String(input + 22): "${String(num + 22)}" (${typeof String(num + 22)})
Number(input) + 22: ${Number(input) + 22} (${typeof (Number(input) + 22)})
Boolean(input): ${Boolean(input)} (${typeof Boolean(input)}) `; // Bảng tham khảo const testValues = [0, 1, -1, "", "hello", "0", "1", null, undefined, [], [1], {}, NaN, Infinity]; let tableHtml = ''; testValues.forEach(v => { tableHtml += ``; }); tableHtml += '
Giá trịString()Number()Boolean()
${JSON.stringify(v)} ${JSON.stringify(String(v))} ${Number(v)} ${Boolean(v)}
'; resEle.innerHTML += '

' + tableHtml; }); </script> </body> </html>

Kết quả

Input: "44" (string)

  • String(44 + 22) = "66" (string)
  • Number("44") + 22 = 66 (number)
  • Boolean("44") = true (boolean)

Bảng chuyển đổi tham khảo:

Giá trịString()Number()Boolean()
0"0"0false
1"1"1true
"" (empty string)""0false
"hello""hello"NaNtrue
"0""0"0true ⚠️
null"null"0false
undefined"undefined"NaNfalse
[]""0true ⚠️
[1]"1"1true
{}"[object Object]"NaNtrue
NaN"NaN"NaNfalse
Infinity"Infinity"Infinitytrue

Best Practice:

  • Dùng String(x), Number(x), Boolean(x) - rõ ràng, không new
  • Tránh new String(), new Number(), new Boolean() (tạo object wrapper)
  • Kiểm tra Number.isNaN(), Number.isFinite() sau khi parse
  • Dùng Number() thay parseInt() khi cần strict (parseInt("42px")=42, Number("42px")=NaN)