JavaScript-ohjelma sen tarkistamiseksi, onko muuttuja toiminnotyyppiä

Tässä esimerkissä opit kirjoittamaan JavaScript-ohjelman, joka tarkistaa, onko muuttuja toiminnotyyppiä.

Tämän esimerkin ymmärtämiseksi sinulla on oltava tieto seuraavista JavaScript-ohjelmoinnin aiheista:

  • Operaattorin JavaScript-tyyppi
  • Javascript-toimintokutsu ()
  • Javascript-objekti merkkijonolle ()

Esimerkki 1: Käyttäjän instanceof käyttö

 // program to check if a variable is of function type function testVariable(variable) ( if(variable instanceof Function) ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Tuotos

 Muuttuja ei ole funktiotyyppiä Muuttuja on funktiotyyppiä

Yllä olevassa ohjelmassa instanceofoperaattoria käytetään tarkistamaan muuttujan tyyppi.

Esimerkki 2: Operaattorin tyypin käyttäminen

 // program to check if a variable is of function type function testVariable(variable) ( if(typeof variable === 'function') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Tuotos

 Muuttuja ei ole funktiotyyppiä Muuttuja on funktiotyyppiä

Yllä olevassa ohjelmassa typeofoperaattoria käytetään ehdottomasti yhtä suureksi kuin ===operaattori muuttujan tyypin tarkistamiseen.

typeofOperaattori antaa muuttuvan tiedon tyyppi. ===tarkistaa, onko muuttuja yhtä suuri arvon sekä tietotyypin suhteen.

Esimerkki 3: Object.prototype.toString.call () -menetelmän käyttö

 // program to check if a variable is of function type function testVariable(variable) ( if(Object.prototype.toString.call(variable) == '(object Function)') ( console.log('The variable is of function type'); ) else ( console.log('The variable is not of function type'); ) ) const count = true; const x = function() ( console.log('hello') ); testVariable(count); testVariable(x);

Tuotos

 Muuttuja ei ole funktiotyyppiä Muuttuja on funktiotyyppiä 

Object.prototype.toString.call()Menetelmä palauttaa merkkijonon, joka määrittelee objektin tyypin.

Mielenkiintoisia artikkeleita...