JavaScript programma, lai pārbaudītu, vai mainīgais ir funkcijas tips

Šajā piemērā jūs iemācīsities rakstīt JavaScript programmu, kas pārbaudīs, vai mainīgais ir funkcija tipa.

Lai saprastu šo piemēru, jums jāpārzina šādas JavaScript programmēšanas tēmas:

  • Operatora JavaScript tips
  • Javascript funkciju izsaukums ()
  • Javascript objekts toString ()

1. piemērs: Operatora instanceof izmantošana

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

Rezultāts

 Mainīgais nav funkcijas tips Mainīgais ir funkcijas tips

Iepriekš minētajā programmā instanceofmainīgā tipa pārbaudei tiek izmantots operators.

2. piemērs: Operator type izmantošana

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

Rezultāts

 Mainīgais nav funkcijas tips Mainīgais ir funkcijas tips

Iepriekš minētajā programmā mainīgā tipa pārbaudei typeoftiek izmantots operators, kas ir pilnīgi vienāds ar ===operatoru.

typeofOperators sniedz mainīgā datu tipu. ===pārbauda, ​​vai mainīgais ir vienāds gan vērtības, gan datu veida ziņā.

3. piemērs: Object.prototype.toString.call () metodes izmantošana

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

Rezultāts

 Mainīgais nav funkcijas tips Mainīgais ir funkcijas tips 

Object.prototype.toString.call()Metode atgriež virkni, kas nosaka objekta veidu.

Interesanti raksti...