În acest tutorial, veți afla despre tipul de operator JavaScript cu ajutorul exemplelor.
typeof
Operatorul returnează tipul de variabile și valori. De exemplu,
const a = 9; console.log(typeof a); // number console.log(typeof '9'); // string console.log(typeof false); // boolean
Sintaxa tipului de Operator
Sintaxa typeof
operatorului este:
typeof operand
Aici, operand este un nume de variabilă sau o valoare.
tipul de tipuri
Tipurile posibile disponibile în JavaScript pe care typeof
operatorul le returnează sunt:
Tipuri | tip de rezultat |
---|---|
String | "şir" |
Number | "număr" |
BigInt | "bigint" |
Boolean | "boolean" |
Object | "obiect" |
Symbol | "simbol" |
undefined | "nedefinit" |
null | "obiect" |
funcţie | "funcţie" |
Exemplul 1: typeof pentru String
const str1 = 'Peter'; console.log(typeof str1); // string const str2 = '3'; console.log(typeof str2); // string const str3 = 'true'; console.log(typeof str3); // string
Exemplul 2: typeof pentru 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
Exemplul 3: typeof pentru BigInt
const bigInt1 = 900719925124740998n; console.log(typeof bigInt1); // bigint const bigInt2 = 1n; console.log(typeof bigInt2); // bigint
Exemplul 4: typeof pentru boolean
const boolean1 = true; console.log(typeof boolean1); // boolean const boolean2 = false; console.log(typeof boolean2); // boolean
Exemplul 5: typeof pentru Nedefinit
let variableName1; console.log(typeof variableName1); // undefined let variableName2 = undefined; console.log(typeof variableName2); // undefined
Exemplul 6: typeof pentru nul
const name = null; console.log(typeof name); // object console.log(typeof null); // object
Exemplul 7: tip de simbol
const symbol1 = Symbol(); console.log(typeof symbol1); // symbol const symbol2 = Symbol('hello'); console.log(typeof symbol2); // symbol
Exemplul 8: tip de obiect
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
Exemplul 9: tip de funcție
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
Utilizări de tip Operator
typeof
Operatorul poate fi folosit pentru a verifica tipul unei variabile la un anumit punct. De exemplu,
let count = 4; console.log(typeof count); count = true; console.log(typeof count);
- Puteți efectua diferite acțiuni pentru diferite tipuri de date. De exemplu,
let count = 4; if(typeof count === 'number') ( // perform some action ) else if (typeof count = 'boolean') ( // perform another action )