I denna handledning lär du dig om JavaScript-typ av operatör med hjälp av exempel.
Den typeof
Operatören återgår den typ av variabler och värden. Till exempel,
const a = 9; console.log(typeof a); // number console.log(typeof '9'); // string console.log(typeof false); // boolean
Syntax för operatörstyp
Syntaxen för typeof
operatören är:
typeof operand
Här är operand ett variabelt namn eller ett värde.
typ av typer
De möjliga typer som finns tillgängliga i JavaScript som typeof
operatören returnerar är:
Typer | typ av resultat |
---|---|
String | "sträng" |
Number | "siffra" |
BigInt | "bigint" |
Boolean | "boolean" |
Object | "objekt" |
Symbol | "symbol" |
undefined | "odefinierad" |
null | "objekt" |
fungera | "fungera" |
Exempel 1: typeof för sträng
const str1 = 'Peter'; console.log(typeof str1); // string const str2 = '3'; console.log(typeof str2); // string const str3 = 'true'; console.log(typeof str3); // string
Exempel 2: typeof för 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
Exempel 3: typeof för BigInt
const bigInt1 = 900719925124740998n; console.log(typeof bigInt1); // bigint const bigInt2 = 1n; console.log(typeof bigInt2); // bigint
Exempel 4: typeof för Boolean
const boolean1 = true; console.log(typeof boolean1); // boolean const boolean2 = false; console.log(typeof boolean2); // boolean
Exempel 5: typeof för odefinierad
let variableName1; console.log(typeof variableName1); // undefined let variableName2 = undefined; console.log(typeof variableName2); // undefined
Exempel 6: typeof för null
const name = null; console.log(typeof name); // object console.log(typeof null); // object
Exempel 7: typof för symbol
const symbol1 = Symbol(); console.log(typeof symbol1); // symbol const symbol2 = Symbol('hello'); console.log(typeof symbol2); // symbol
Exempel 8: typeof för Object
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
Exempel 9: typeof för Funktion
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
Användning av typ av operatör
- Den
typeof
Operatören kan användas för att kontrollera vilken typ av en variabel vid en viss punkt. Till exempel,
let count = 4; console.log(typeof count); count = true; console.log(typeof count);
- Du kan utföra olika åtgärder för olika typer av data. Till exempel,
let count = 4; if(typeof count === 'number') ( // perform some action ) else if (typeof count = 'boolean') ( // perform another action )