js判断是否为空和typeof的用法
(1)typeof作用
用于查看数据类型
(2)typeof用法
typeof 返回值类型有number, string, boolean, function, undefined, object
PS:在使用typeof()操作符时圆括号是可选项,可带可不带。即两种形式 typeof(XX) 或 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只能区分number, string, boolean, function及undefined,其他的对象、数组、日期、null等都返回Object,存在缺陷。
利用Object.prototype.toString.call可以很好的区分各种类型(注:无法区分自定义对象类型,自定义类型可以采用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]
(3)js判断是否为空
1 var exp = null;
2 if (!exp && typeof(exp)!="undefined" && exp!=0 && exp!='')
3 {
4 alert("is not null");
5 }