(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 }