JavaScript-Programm zum Überprüfen, ob eine Variable vom Funktionstyp ist

In diesem Beispiel lernen Sie, ein JavaScript-Programm zu schreiben, das prüft, ob eine Variable vom Funktionstyp ist.

Um dieses Beispiel zu verstehen, sollten Sie die folgenden JavaScript-Programmierthemen kennen:

  • JavaScript-Typ des Operators
  • Javascript Funktionsaufruf ()
  • Javascript Object toString ()

Beispiel 1: Verwenden der Instanz des Operators

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

Ausgabe

 Die Variable ist nicht vom Funktionstyp. Die Variable ist vom Funktionstyp

Im obigen Programm wird der instanceofOperator verwendet, um den Variablentyp zu überprüfen.

Beispiel 2: Verwenden des Operatortyps

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

Ausgabe

 Die Variable ist nicht vom Funktionstyp. Die Variable ist vom Funktionstyp

Im obigen Programm wird der typeofOperator mit dem Operator strict gleich verwendet ===, um den Variablentyp zu überprüfen.

Der typeofOperator gibt den variablen Datentyp an. ===prüft, ob die Variable sowohl hinsichtlich des Wertes als auch des Datentyps gleich ist.

Beispiel 3: Verwenden der Object.prototype.toString.call () -Methode

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

Ausgabe

 Die Variable ist nicht vom Funktionstyp. Die Variable ist vom Funktionstyp 

Die Object.prototype.toString.call()Methode gibt eine Zeichenfolge zurück, die den Objekttyp angibt.

Interessante Beiträge...