Type:
There are seven built-in types in JavaScript:
- A null value (null)
- Undefined (undefined)
- Boolean value (Boolean)
- Number (number)
- String (string)
- Object (object)
- Symbol (new in ES6)
In JS, there are a lot of pits, this article will combine undersoce.js source code and I summarized the method to accurately judge the six types, the seventh will also provide a judgment thinking;
Here’s a quick quiz:
First, there’s the familiar typeof, an old but useful way of judging:
typeof null // "object"<= In the later article you will see, giant pit!! typeof undefined //"undefined"
typeof true // "boolean"
typeof 42 // "number"
typeof "42" // "string"
typeof {life: 42} // "object"
typeof Symbol() // "symbol"/ / -- -- -- -- -- -- -- -- -- -- -- -- three was put forward by separate considerations behind -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- typeof void 0 / /"undefined"<= This is a very useful technique, which I'll explain later; Typeof [1, 2, 3] / /"object"<= array is actually an object, pit!! typeoffunction a() { } // "function"
Copy the code
Skillfully use “!” No. :
! null //true<= This is a very clever trick, as explained below; ! undefined //true<= This is a very clever trick, as explained below; ------------ we are different!! -- -- -- -- -- -- -- -- -- -- -- --! 123 / /false
!true // false! {a: 123} //false
!function a() { } // false
!'123' // false
Copy the code
With this distinction, we can do some interesting things, a trick we learned in the undersoce.js source code, to accurately exclude null and undefined
.tostring.call () :
Of course Object. The prototype. ToString. Call can also change the Object. The prototype. ToString. Apply.
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(123) // "[object Number]"
Object.prototype.toString.call(true) / /"[object Boolean]"
Object.prototype.toString.call('123') / /"[object String]"
Object.prototype.toString.call({a: 123}) // "[object Object]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"/ / -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- alone out of several matters needing attention -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - the Object. The prototype. ToString. Call / / ([1, 2, 3])"[object Array]"
Object.prototype.toString.call(function a/ / () {})"[object Function]"Actually function also is the object type object. The prototype. ToString. Call (new Date) / /"[object Date]"Date Object Object. The prototype. ToString. Call (Math) / / [Object Math] mathematical function Object Object. The prototype. ToString. Call (function a/ / () {})"[object Function]"The function is also of type objectCopy the code
Note 1: There are compatibility problems in this method, click for specific compatibility problemshereJavaScript 1.8.5 cannot fully detect the above situation.
Note 2: Using this technique, these 7 types and more can be accurately distinguished, whereas Typeof cannot distinguish completely !!!!!
Take a look at “constructor” :
The way to do that is to figure out what the object’s constructor is, and I’ll talk about what the constructor is in another article;
var n1 = null; // error: null is the starting point of the JS prototype chain, no constructor; var u = undefined; // Error: it also has no constructor; var a = [1, 2, 3]; a.constructor === Array; //trueArray var n = 123; n.constructor === Number; //trueThe number var s1 ='123';
abc.constructor === String // trueString var o = {a: 123}; o.constructor === Object; //trueConstructor === Symbol //trueSymbol -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- separate out about several matters needing attention -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the var arr = [1, 2, 3]; arr.constructor === Array //trueArrays do a good job of differentiating var fun =function a() {}; fun.constructor === Function //trueVar ABC = new Date(); abc.constructor === Date; //trueVar ABC = new RegExp(); abc.constructor === RegExp; //trueConstructor === Math; //falseMay not be as Object. The prototype. ToString. Call (); abc.constructor === Object //trueThere is actually no Math constructor; Math's constructor is on ObjectCopy the code
The final “instanceof” :
Note: The use object must be an object;
// Syntax: object instanceof constructor; var n1 = 123; // n is an element of type Number!! Not an object!! typeof n1; //"number"Recall that we have 7 types n1 instanceof Number; //false function Number() {} var n2 = new Number(123) typeof n2; //"object"
n2 instanceof Number; // true
Copy the code
As mentioned above, this method is only suitable for judging objects!!
var a = [1, 2, 3]; // Array is also an object. a instanceof Array; // The object's constructor isfunction Array() {} // Even though typeof null is object, it is the lowest level elementCopy the code
If you don’t know anything about prototype chains, remember that instanceof can judge arrays!!
Methods 1 are all derived from underscore. Js
A null value (null) :
Method 1: Use strict equality directly.
var isNull = function (obj) {
return obj === null;
};
Copy the code
This is the most direct and effective way;
Law 2: Use it wisely! The result of null is true:
var isNull = function (obj) {
return! obj && typeof obj ==="object";
};
Copy the code
Although this method is clever, it is not as direct as method 1;
Undefined (undefined)
This is the most recommended way.
var isUndefined = function (obj) {
return obj === void 0;
}
Copy the code
Many common tool libraries use this method, highly recommended!! ;
Method 2: Use typeof directly to judge:
var isUndefined = function (obj) {
return typeof obj === "undefined";
}
Copy the code
This way, it is also relatively stable;
Note:
- Undefined cannot be modified globally.
- Undefined in local conditions can be modified under certain circumstances.
- Please poke here hard for the official documentation.
(function(undefined) {
console.log(undefined); // "123"}) ('123')
Copy the code
Boolean value (Boolean)
Why does underscore. Js make such a judgment? Readers know that they can contact me;
var toString = Object.prototype.toString;
var isBoolean = function (obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
}
Copy the code
Similarly, we can make judgments using.constructor and typeof.
Number (number)
var toString = Object.prototype.toString;
var isNumber = function (obj) {
return toString.call(obj) === '[object Number]';
}
Copy the code
Similarly, we can implement judgments using constructor and Typeof approaches.
String (string)
var toString = Object.prototype.toString;
var isString = function (obj) {
return toString.call(obj) === '[object String]';
}
Copy the code
Similarly, we can implement judgments using constructor and Typeof approaches.
Object (object)
var toString = Object.prototype.toString;
var isObject = function (obj) {
var type = typeof obj;
return type= = ='function' || type= = ='object'&&!!!!! obj; }Copy the code
Here, is my most confused place, why to use!! Obj?
typeof null === object
The results fortrue
;- I’ve talked about one at the beginning,
! obj
The way,null
和undefined
The return result istrue
The other types are false; - In the implementation above, if the passed value is
null
When, will be by!!!!! obj
Filter out;
Or try &&!! Obj, let’s see if it works.
Other:
Date, Math, RegExp, etc. Built-in objects are not used in detail.
Array (Array)
Law 1: The safest way:
Object. The prototype. ToString. Call / / ([1, 2, 3])"[object Array]"
Copy the code
Use this method honestly!!
Method 2: Instanceof method, for extension only:
var a = [1, 2, 3]; // Array is also an object. a instanceof Array; // The object's constructor isfunction Array() {}Copy the code
Method 3: constructor method, for extension only
var a = [1, 2, 3];
a.constructor === Array; // trueAn array ofCopy the code
Note: if a = null, an error will be reported, this method is not recommended!!
Method 4: Check the constructor of the prototype, only to extend:
var a = [1, 2, 3];
a.__proto__.constructor === Array
Copy the code
In fact, methods 2 to 4 are all part of the same idea, to determine whether the object constructor is an array, but the implementation is different.
References and acknowledgements:
- JavaScript you Don’t Know (Middle);
- The Underscore. Js source;
- http://www.jb51.net/article/79939.htm
- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript