Trong hướng dẫn này, bạn sẽ tìm hiểu về toán tử typeof JavaScript với sự trợ giúp của các ví dụ.
Các typeof
nhà điều hành trả về kiểu của các biến và giá trị. Ví dụ,
const a = 9; console.log(typeof a); // number console.log(typeof '9'); // string console.log(typeof false); // boolean
Cú pháp của toán tử typeof
Cú pháp của typeof
toán tử là:
typeof operand
Ở đây, toán hạng là một tên biến hoặc một giá trị.
typeof các loại
Các kiểu có thể có trong JavaScript mà typeof
toán tử trả về là:
Các loại | typeof Kết quả |
---|---|
String | "chuỗi" |
Number | "con số" |
BigInt | "bigint" |
Boolean | "boolean" |
Object | "vật" |
Symbol | "Biểu tượng" |
undefined | "chưa xác định" |
null | "vật" |
chức năng | "chức năng" |
Ví dụ 1: typeof cho chuỗi
const str1 = 'Peter'; console.log(typeof str1); // string const str2 = '3'; console.log(typeof str2); // string const str3 = 'true'; console.log(typeof str3); // string
Ví dụ 2: typeof cho Number
const number1 = 3; console.log(typeof number1); // number const number2 = 3.433; console.log(typeof number2); // number const number3 = 3e5 console.log(typeof number3); // number const number4 = 3/0; console.log(typeof number4); // number
Ví dụ 3: typeof cho BigInt
const bigInt1 = 900719925124740998n; console.log(typeof bigInt1); // bigint const bigInt2 = 1n; console.log(typeof bigInt2); // bigint
Ví dụ 4: typeof cho Boolean
const boolean1 = true; console.log(typeof boolean1); // boolean const boolean2 = false; console.log(typeof boolean2); // boolean
Ví dụ 5: typeof cho Undefined
let variableName1; console.log(typeof variableName1); // undefined let variableName2 = undefined; console.log(typeof variableName2); // undefined
Ví dụ 6: typeof cho null
const name = null; console.log(typeof name); // object console.log(typeof null); // object
Ví dụ 7: typeof cho Symbol
const symbol1 = Symbol(); console.log(typeof symbol1); // symbol const symbol2 = Symbol('hello'); console.log(typeof symbol2); // symbol
Ví dụ 8: typeof cho đối tượng
let obj1 = (); console.log(typeof obj1); // object let obj2 = new String(); console.log(typeof obj2); // object let obj3 = (1, 3, 5, 8); console.log(typeof obj3); // object
Ví dụ 9: typeof cho Hàm
let func = function () (); console.log(typeof func); // function // constructor function console.log(typeof String); // function console.log(typeof Number); // function console.log(typeof Boolean); // function
Sử dụng toán tử typeof
- Các
typeof
nhà điều hành có thể được sử dụng để kiểm tra các loại của một biến tại một điểm cụ thể. Ví dụ,
let count = 4; console.log(typeof count); count = true; console.log(typeof count);
- Bạn có thể thực hiện các hành động khác nhau cho các loại dữ liệu khác nhau. Ví dụ,
let count = 4; if(typeof count === 'number') ( // perform some action ) else if (typeof count = 'boolean') ( // perform another action )