Testing Type in Jquery

by Vickram H 2012-09-04 09:32:09

Testing Type in Jquery:


JavaScript offers a way to test the "type" of a variable. However, the result can be confusing — for example, the type of an Array is "object".

Sample Code:

01 var myFunction = function() {
02 console.log('hello');
03 };
04
05 var myObject = {
06 foo : 'bar'
07 };
08
09 var myArray = [ 'a', 'b', 'c' ];
10
11 var myString = 'hello';
12
13 var myNumber = 3;
14
15 typeof myFunction; // returns 'function'
16 typeof myObject; // returns 'object'
17 typeof myArray; // returns 'object' -- careful!
18 typeof myString; // returns 'string';
19 typeof myNumber; // returns 'number'
20
21 typeof null; // returns 'object' -- careful!
22
23
24 if (myArray.push && myArray.slice && myArray.join) {
25 // probably an array
26 // (this is called "duck typing")
27 }
28
29 if (Object.prototype.toString.call(myArray) === '[object Array]') {
30 // Definitely an array!
31 // This is widely considered as the most robust way
32 // to determine if a specific value is an Array.
33 }

Tagged in:

815
like
0
dislike
0
mail
flag

You must LOGIN to add comments