js判断是否为空和typeof的用法

本文详细介绍了JavaScript中typeof操作符的用途和用法,包括其返回的各种数据类型如number、string、boolean等,并指出其在判断某些类型时存在的缺陷。同时,文章提供了使用Object.prototype.toString.call方法来更准确地识别不同类型的解决方案。最后,文中还包含了一个判断变量是否为空的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值