js determine whether the use of empty and typeof

(1) typeof action
for viewing data type

(2) Usage typeof
typeof Return Value types Number, String, Boolean, function, undefined, Object
the PS: When using typeof () operator parentheses is optional, may be with or without. I.e. two forms typeof (XX) or typeof XX

1  console.log(typeof 2); // number
2  console.log(typeof "2"); // string
3  console.log(typeof true); // boolean
4  console.log(typeof [2]); // object
5  console.log(typeof {name:2});// object
6  console.log(typeof function(){return 2});// function
7  console.log(typeof new Date());// object
8  console.log(typeof null); // object
9  console.log(typeof undefined);// undefined

Typeof but can only differentiate number, string, boolean, function and undefined, other objects, arrays, date, null and so returns Object, flawed.
Object.prototype.toString.call using various types can be well distinguished (Note: custom object types can not be distinguished, custom types may be employed to distinguish instanceof)

 1 console.log(Object.prototype.toString.call("zhangsan"));//[object String]
 2 console.log(Object.prototype.toString.call(12));//[object Number]
 3 console.log(Object.prototype.toString.call(true));//[object Boolean]
 4 console.log(Object.prototype.toString.call(undefined));//[object Undefined]
 5 console.log(Object.prototype.toString.call(null));//[object Null]
 6 console.log(Object.prototype.toString.call({name: "zhangsan"}));//[object Object]
 7 console.log(Object.prototype.toString.call(function(){}));//[object Function]
 8 console.log(Object.prototype.toString.call([]));//[object Array]
 9 console.log(Object.prototype.toString.call(new Date));//[object Date]
10 console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
11 function Person(){};
12 console.log(Object.prototype.toString.call(new Person));//[object Object]

If (3) js determined null

1 var exp = null; 
2 if (!exp && typeof(exp)!="undefined" && exp!=0 && exp!='') 
3 { 
4   alert("is not null"); 
5 } 

 

Guess you like

Origin www.cnblogs.com/xmm2017/p/11470323.html