(1)typeof作用
用于查看数据类型
(2)typeof用法
typeof 返回值类型有number, string, boolean, function, undefined, object
PS:在使用typeof()操作符时圆括号是可选项,可带可不带。即两种形式 typeof(XX) 或 typeof XX
console.log(typeof 2); // number
console.log(typeof "2"); // string
console.log(typeof true); // boolean
console.log(typeof [2]); // object
console.log(typeof {name:2});// object
console.log(typeof function(){return 2});// function
console.log(typeof new Date());// object
console.log(typeof null); // object
console.log(typeof undefined);// undefined
但typeof只能区分number, string, boolean, function及undefined,其他的对象、数组、日期、null等都返回Object,存在缺陷。
利用Object.prototype.toString.call可以很好的区分各种类型(注:无法区分自定义对象类型,自定义类型可以采用instanceof区分)
console.log(Object.prototype.toString.call("zhangsan"));//[object String]
console.log(Object.prototype.toString.call(12));//[object Number]
console.log(Object.prototype.toString.call(true));//[object Boolean]
console.log(Object.prototype.toString.call(undefined));//[object Undefined]
console.log(Object.prototype.toString.call(null));//[object Null]
console.log(Object.prototype.toString.call({name: "zhangsan"}));//[object Object]
console.log(Object.prototype.toString.call(function(){}));//[object Function]
console.log(Object.prototype.toString.call([]));//[object Array]
console.log(Object.prototype.toString.call(new Date));//[object Date]
console.log(Object.prototype.toString.call(/\d/));//[object RegExp]
function Person(){};
console.log(Object.prototype.toString.call(new Person));//[object Object]
(3)js判断是否为空
var exp = null;
if (!exp && typeof(exp)!="undefined" && exp!=0 && exp!='')
{
alert("is not null");
}
参考:https://www.cnblogs.com/youhong/p/6209054.html