जावास्क्रिप्ट प्रोग्राम यह जाँचने के लिए कि क्या चर प्रकार का है

इस उदाहरण में, आप एक जावास्क्रिप्ट प्रोग्राम लिखना सीखेंगे जो यह जाँच करेगा कि कोई चर फ़ंक्शन प्रकार का है या नहीं।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावास्क्रिप्ट प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावास्क्रिप्ट टाइपो ऑपरेटर
  • जावास्क्रिप्ट फ़ंक्शन कॉल ()
  • जावास्क्रिप्ट ऑब्जेक्ट

उदाहरण 1: Instof Operator का उपयोग करना

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

आउटपुट

 वेरिएबल फंक्शन टाइप का नहीं होता है वेरिएबल फंक्शन टाइप का होता है

उपरोक्त कार्यक्रम में, instanceofऑपरेटर का उपयोग चर के प्रकार की जांच करने के लिए किया जाता है।

उदाहरण 2: टाइपोफ़ ऑपरेटर का उपयोग करना

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

आउटपुट

 वेरिएबल फंक्शन टाइप का नहीं होता है वेरिएबल फंक्शन टाइप का होता है

उपरोक्त कार्यक्रम में, ऑपरेटर को चर के प्रकार की जांच करने के typeofलिए ===ऑपरेटर के बराबर सख्त के साथ प्रयोग किया जाता है ।

typeofऑपरेटर चर डेटा प्रकार देता है। ===जाँचता है कि क्या चर मान के साथ-साथ डेटा प्रकार के बराबर है।

उदाहरण 3: Object.prototype.toString.call () विधि का उपयोग करना

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

आउटपुट

 वेरिएबल फंक्शन टाइप का नहीं होता है वेरिएबल फंक्शन टाइप का होता है 

Object.prototype.toString.call()विधि एक स्ट्रिंग है कि वस्तु प्रकार निर्दिष्ट देता है।

दिलचस्प लेख...