JavaScripti programm, et kontrollida, kas muutuja on funktsiooni tüüpi

Selles näites õpid kirjutama JavaScripti programmi, mis kontrollib, kas muutuja on funktsiooni tüüpi.

Selle näite mõistmiseks peaksid teil olema teadmised järgmistest JavaScripti programmeerimise teemadest:

  • Operaatori JavaScripti tüüp
  • Javascripti funktsioonikõne ()
  • Javascripti objekt toStringile ()

Näide 1: Operaatori instanceofi kasutamine

 // 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);

Väljund

 Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi

Ülaltoodud programmis instanceofkasutatakse muutuja tüübi kontrollimiseks operaatorit.

Näide 2: Operaatori typeof kasutamine

 // 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);

Väljund

 Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi

Ülaltoodud programmis typeofkasutatakse ===muutujatüübi kontrollimiseks operaatorit operaatoriga võrdselt .

typeofOperaator annab muutuja andmetüüp. ===kontrollib, kas muutuja on väärtuselt ja andmetüübilt võrdne.

Näide 3: meetodi Object.prototype.toString.call () kasutamine

 // 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);

Väljund

 Muutuja ei ole funktsiooni tüüpi Muutuja on funktsiooni tüüpi 

Object.prototype.toString.call()Meetod tagastab stringi, mis määrab objekti tüübist.

Huvitavad Artiklid...