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àm | Chuyển thành | Ví dụ | Kết quả |
|---|---|---|---|
String() | String | String(123) | "123" |
Number() | Number | Number("123") | 123 |
Boolean() | Boolean | Boolean(1) | true |
BigInt() | BigInt | BigInt(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 = 'Giá trị String() Number() Boolean() ';
testValues.forEach(v => {
tableHtml += `
${JSON.stringify(v)}
${JSON.stringify(String(v))}
${Number(v)}
${Boolean(v)}
`;
});
tableHtml += '
';
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" | 0 | false |
1 | "1" | 1 | true |
"" (empty string) | "" | 0 | false |
"hello" | "hello" | NaN | true |
"0" | "0" | 0 | true ⚠️ |
null | "null" | 0 | false |
undefined | "undefined" | NaN | false |
[] | "" | 0 | true ⚠️ |
[1] | "1" | 1 | true |
{} | "[object Object]" | NaN | true |
NaN | "NaN" | NaN | false |
Infinity | "Infinity" | Infinity | true |
Best Practice:
- Dùng
String(x),Number(x),Boolean(x)- rõ ràng, khôngnew - 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()thayparseInt()khi cần strict (parseInt("42px")=42, Number("42px")=NaN)