Typ operátora JavaScript

V tomto výučbe sa pomocou príkladov dozviete o operátore typu JavaScript.

typeofOperátor vráti typ premenných a hodnôt. Napríklad,

 const a = 9; console.log(typeof a); // number console.log(typeof '9'); // string console.log(typeof false); // boolean

Syntax typu operátor

Syntax typeofoperátora je:

 typeof operand

V tomto prípade je operandom názov premennej alebo hodnota.

typ typov

Možné typy dostupné v JavaScripte, ktoré typeofoperátor vráti, sú:

Typy typ výsledku
String "reťazec"
Number „číslo“
BigInt "bigint"
Boolean „boolovský“
Object „objekt“
Symbol „symbol“
undefined „nedefinované“
null „objekt“
funkcia "funkcia"

Príklad 1: typ písma pre reťazec

 const str1 = 'Peter'; console.log(typeof str1); // string const str2 = '3'; console.log(typeof str2); // string const str3 = 'true'; console.log(typeof str3); // string

Príklad 2: Typeof pre 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 

Príklad 3: typ písma pre BigInt

 const bigInt1 = 900719925124740998n; console.log(typeof bigInt1); // bigint const bigInt2 = 1n; console.log(typeof bigInt2); // bigint

Príklad 4: typeof pre Boolean

 const boolean1 = true; console.log(typeof boolean1); // boolean const boolean2 = false; console.log(typeof boolean2); // boolean

Príklad 5: Typeof pre Undefined

 let variableName1; console.log(typeof variableName1); // undefined let variableName2 = undefined; console.log(typeof variableName2); // undefined

Príklad 6: typeof pre null

 const name = null; console.log(typeof name); // object console.log(typeof null); // object

Príklad 7: typ písma pre Symbol

 const symbol1 = Symbol(); console.log(typeof symbol1); // symbol const symbol2 = Symbol('hello'); console.log(typeof symbol2); // symbol

Príklad 8: Typeof pre 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

Príklad 9: typ funkcie

 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

Použitie typu operátora

  • Pomocou typeofoperátora je možné skontrolovať typ premennej v konkrétnom bode. Napríklad,
 let count = 4; console.log(typeof count); count = true; console.log(typeof count);
  • Pre rôzne typy údajov môžete vykonať rôzne akcie. Napríklad,
 let count = 4; if(typeof count === 'number') ( // perform some action ) else if (typeof count = 'boolean') ( // perform another action )

Zaujímavé články...