JavaScript TypeOf - كيفية التحقق من نوع متغير أو كائن في JS
تعد أنواع البيانات وفحص النوع من الجوانب الأساسية لأي لغة برمجة.
العديد من لغات البرمجة مثل Java لديها فحص صارم للأنواع. هذا يعني أنه إذا تم تعريف متغير بنوع معين ، فيمكن أن يحتوي على قيمة من هذا النوع فقط.
جافا سكريبت ، مع ذلك ، هي لغة مكتوبة بشكل فضفاض (أو مكتوبة ديناميكيًا). هذا يعني أن المتغير يمكن أن يحتوي على قيمة من أي نوع. يمكن تنفيذ تعليمات JavaScript البرمجية على النحو التالي:
let one = 1; one = 'one'; one = true; one = Boolean(true); one = String('It is possible');
مع وضع هذا في الاعتبار ، من المهم معرفة نوع المتغير في أي وقت.
يتم تحديد نوع المتغير حسب نوع القيمة المخصصة له. JavaScript لها عامل تشغيل خاص يسمى typeof
والذي يتيح لك الحصول على نوع أي قيمة.
في هذه المقالة ، سوف نتعلم كيف typeof
يتم استخدامها ، جنبًا إلى جنب مع بعض المشاكل التي يجب الانتباه إليها.
أنواع بيانات JavaScript
دعنا نلقي نظرة سريعة على أنواع بيانات JavaScript قبل البحث في typeof
المشغل.
في JavaScript ، هناك سبعة أنواع بدائية. البيانات الأولية هي البيانات التي ليست كائنًا وليس لها طرق. هم انهم:
- خيط
- رقم
- BigInt
- رمز
- قيمة منطقية
- غير معرف
- لا شيء
كل شيء آخر object
- حتى بما في ذلك array
و function
. نوع الكائن هو مجموعة من أزواج المفتاح والقيمة.
نوع مشغل JavaScript
في typeof
المشغل يأخذ المعامل واحد فقط (عامل تشغيل الأحادية) ويقيم نوعه للعودة نوع كسلسلة. إليك كيفية استخدامه عند تقييم نوع الرقم 007.
typeof 007; // returns 'number'
هناك بناء جملة بديل typeof
للمشغل حيث يمكنك استخدامه مثل function
:
typeof(operand)
يكون بناء الجملة هذا مفيدًا عندما تريد تقييم تعبير بدلاً من قيمة واحدة. هذا مثال على ذلك:
typeof(typeof 007); // returns 'string'
في المثال أعلاه ، يتم typeof 007
تقييم التعبير إلى رقم النوع وإرجاع السلسلة النصية 'number'. typeof('number')
ثم ينتج عنها 'string'
.
لنلق نظرة على مثال آخر لفهم أهمية الأقواس مع typeof
عامل التشغيل.
typeof(999-3223); // returns, "number"
إذا حذفت القوس ، فسيعود ، NaN
(ليس رقمًا):
typeof 999-3223; // returns, NaN
هذا لأنه ، أولاً typeof 999
سينتج عن سلسلة ، "رقم". "number" - 32223
ينتج عن التعبير NaN كما يحدث عند إجراء عملية طرح بين سلسلة ورقم.
نوع جافا سكريبت من الأمثلة
يوضح الكود التالي فحص النوع للقيم المختلفة باستخدام typeof
عامل التشغيل.
typeof 0; //'number' typeof +0; //'number' typeof -0; //'number' typeof Math.sqrt(2); //'number' typeof Infinity; //'number' typeof NaN; //'number', even if it is Not a Number typeof Number('100'); //'number', After successfully coerced to number typeof Number('freeCodeCamp'); //'number', despite it can not be coerced to a number typeof true; //'boolean' typeof false; //'boolean' typeof Boolean(0); //'boolean' typeof 12n; //'bigint' typeof ''; //'string' typeof 'freeCodeCamp'; //'string' typeof `freeCodeCamp is awesome`; //'string' typeof '100'; //'string' typeof String(100); //'string' typeof Symbol(); //'symbol' typeof Symbol('freeCodeCamp'); //'symbol' typeof {blog: 'freeCodeCamp', author: 'Tapas A'}; //'object'; typeof ['This', 'is', 101]; //'object' typeof new Date(); //'object' typeof Array(4); //'object' typeof new Boolean(true); //'object'; typeof new Number(101); //'object'; typeof new String('freeCodeCamp'); //'object'; typeof new Object; //'object' typeof alert; //'function' typeof function () {}; //'function' typeof (() => {}); //'function' - an arrow function so, parenthesis is required typeof Math.sqrt; //'function' let a; typeof a; //'undefined' typeof b; //'undefined' typeof undefined; //'undefined' typeof null; //'object'
يلخص الجدول أدناه قيم الإرجاع المحتملة لـ typeof
:
نوع | قيمة الإرجاع من typeof |
---|---|
خيط | 'string' |
رقم | 'number' |
BigInt | 'bigint' |
رمز | 'symbol' |
قيمة منطقية | 'boolean' |
غير معرف | 'undefined' |
كائن الوظيفة | 'function' |
لا شيء | 'object' (انظر أدناه!) |
أي أشياء أخرى | 'object' |
مسك مشتركة مع typeof
هناك حالات typeof
قد لا يقوم فيها عامل التشغيل بإرجاع الأنواع التي تتوقعها. قد يتسبب هذا في حدوث ارتباك وأخطاء. فيما يلي بعض الحالات.
نوع NaN هو رقم
typeof NaN; //'number', even if it is Not a Number
و typeof NaN
هو 'number'
. هذا غريب ، حيث لا ينبغي أن نكتشف NaN
استخدام typeof
. هناك طرق أفضل للتعامل معها. سنراهم في دقيقة.
نوع null
الكائن
typeof null; //'object'
في JavaScript ، typeof null
هو كائن يشير بشكل خاطئ إلى أن القيمة الخالية هي كائن حيث تكون قيمة أولية.
هذا في الواقع خطأ في اللغة وتم إجراء محاولة لإصلاحه. ولكن تم رفضه بسبب مشكلات التوافق مع الإصدارات السابقة.
نوع المتغير غير معرّف غير معرف
قبل ES6 ، يتم استخدام فحص نوع على متغير غير معرّف ينتج عنه 'undefined'
. لكن هذه ليست طريقة آمنة من الأخطاء للتعامل معها.
باستخدام ES6 ، يمكننا الإعلان عن متغيرات ذات نطاق الكتلة باستخدام let
أو const
الكلمات الرئيسية. إذا رأيتها مع عامل التشغيل typeof قبل أن تتم تهيئتها ، فسيتم طرح ملف ReferenceError
.
typeof cat; // ReferenceError let cat = 'brownie';
نوع دالة المُنشئ كائن
Function
ستظل جميع وظائف المُنشئ ، باستثناء التابع constructor ، دائمًا typeof
"object".
typeof new String('freeCodeCamp'); //'object'
This may lead to some confusion, as we expect it to be the actual type (in the above example, a string
type).
The type of an Array is an object
Though technically correct, this could be the most disappointing one. We want to differentiate between an Array and Object even if an Array is technically an Object in JavaScript.
typeof Array(4); //'object'
Fortunately there are ways to detect an Array correctly. We will see that soon.
Beyond typeof
– Better Type Checking
Now that we've seen some of the limitations with the typeof
operator, let's see how to fix them and do better type checking.
How to Detect NaN
In JavaScript, NaN
is a special value. The value NaN represents an outcome when the result of an arithmetic expression can not be represented. For example,
let result = 0/0; console.log(result); // returns, NaN
Also, if we perform any arithmetic operations that involve NaN
, it will always result in a NaN
.
console.log(NaN + 3); // returns, NaN
The type checking on NaN using the typeof
operator doesn't help much as it returns the type as a 'number'
. JavaScript has a global function called isNaN()
to detect if a result is NaN.
isNaN(0/0); // returns, true
But there is a problem here, too.
isNaN(undefined); // returns true for 'undefined'
In ES6, the method isNaN()
is added to the global Number
object. This method is much more reliable and so it's the preferred one.
Number.isNaN(0/0); // returns, true Number.isNaN(undefined); // returns, false
Another interesting aspect of NaN
is that it is the only JavaScript value that is never equal to any other values including itself. So this is another way to detect NaN for the environments where ES6 is not supported:
function isNaN (input) { return input !== input; }
How to Detect null in JavaScript
As we have seen, detecting null using the typeof
operator is not useful. The preferred way to check if something is null is by using the strict equality operator(===
).
function isNull(input) { return input === null; }
Make sure not to use the ==
by mistake. Using the ==
in place of ===
will result in misleading type detection.
How to Detect an Array in JavaScript
From ES6 onwards, we can detect an array using the Array.isArray
method.
Array.isArray([]); // returns true Array.isArray({}); // returns false
Prior to ES6, we could use the instanceof
operator to determine an Array:
function isArray(input) { return input instanceof Array; }
A Generic Solution to Type Checking in JavaScript
There is a way we can create a generic solution to type checking. Have a look at the method, Object.prototype.toString
. This is very powerful and extremely useful for writing a utility method for type checking.
When Object.prototype.toString
is invoked on a value using call()
or apply()
, it returns the object type in the format: [object Type]
. The Type
in the return value is the actual type.
Let's see how it works with some examples:
// returns '[object Array]' Object.prototype.toString.call([]); // returns '[object Date]' Object.prototype.toString.call(new Date()); // returns '[object String]' Object.prototype.toString.call(new String('freeCodeCamp')); // returns '[object Boolean]' Object.prototype.toString.call(new Boolean(true)); // returns '[object Null]' Object.prototype.toString.call(null);
So this means that if we just take the return string and take out the Type
part, we will have the actual type. Here is an attempt to do this:
function typeCheck(value) { const return_value = Object.prototype.toString.call(value); // we can also use regex to do this... const type = return_value.substring( return_value.indexOf(" ") + 1, return_value.indexOf("]")); return type.toLowerCase(); }
Now, we can use the typeCheck
function to detect the types:
typeCheck([]); // 'array' typeCheck(new Date()); // 'date' typeCheck(new String('freeCodeCamp')); // 'string' typeCheck(new Boolean(true)); // 'boolean' typeCheck(null); // 'null'
In Summary
To Summarize what we've learned in this article:
- JavaScript type checking is not as strict as other programming languages.
- Use the
typeof
operator for detecting types. - There are two variants of the
typeof
operator syntax:typeof
andtypeof(expression)
. typeof
قد تكون نتيجة عامل التشغيل مضللة في بعض الأحيان. نحن في حاجة إلى الاعتماد على الوسائل المتاحة الأخرى (Number.isNaN
،Array.isArry
وهلم جرا) في تلك الحالات.- يمكننا استخدامها
Object.prototype.toString
لإنشاء طريقة اكتشاف نوع عام.
قبل أن ننتهي ...
شكرا لك على قراءة هذا الآن! دعنا نتواصل. يمكنك @ me على Twitter (tapasadhikary) مع التعليقات.
قد تعجبك أيضًا هذه المقالات الأخرى:
- JavaScript undefined and null: فلنتحدث عنه للمرة الأخيرة!
- JavaScript: مقارنة المساواة مع == و === و Object.is
- شرح JavaScript `هذه` Keyword + 5 قواعد ربط أساسية للمبتدئين في JS
هذا كل شئ حتى الان. نراكم مرة أخرى مع مقالتي القادمة قريبا. حتى ذلك الحين ، من فضلك اعتني بنفسك جيدًا.