JS 判断数据类型方法

JS 判断数据类型方法

基本类型:String Number Boolean Symbol Undefined Null
引用类型:Object Array Date Function RegExp

方法 1(推荐):toString

// 对于 Object 对象,直接调用 toString() 就能返回 [object Object] 
new Object().toString(); // [object Object]

// 而对于其他对象,则需要通过 call / apply 来调用才能返回正确的类型信息
Object.prototype.toString.call(''); // [object String]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(Symbol()); // [object Symbol]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(new Date()); // [object Date]
Object.prototype.toString.call(new Function()); // [object Function]
Object.prototype.toString.call(new RegExp()); // [object RegExp]
Object.prototype.toString.call(new Error()); // [object Error]
Object.prototype.toString.call(document); // [object HTMLDocument]
Object.prototype.toString.call(window); // [object Window]

方法 2: typeof - 只能区分部分类型.

// 可区分开的类型
typeof ''; // string
typeof 1; // number
typeof true; // boolean
typeof Symbol(); // symbol
typeof undefined; // undefined
typeof {}; // object
typeof new Function(); // function
// 无法区分
typeof null; // object
typeof []; // object
typeof new Date(); // object
typeof new RegExp(); // object

方法 3:constructor - 只能区分部分类型

''.constructor === String; // true
new Number(1).constructor === Number; // true
true.constructor === Boolean; // true
new Object().constructor === Object; // true
[].constructor === Array; // true
new Date().constructor === Date; // true
new Function().constructor === Function; // true
// `null` 和 `undefined` 是无效的对象,因此是不会有 `constructor` 存在的
// 函数的 `constructor` 是不稳定的,这个主要体现在自定义对象上,当重写 `prototype` 后,原有的 `constructor` 引用会丢失,会默认为 `Object`

方法 4: instanceof - 只能用来判断两个对象是否属于实例关系, 而不能判断一个对象实例具体属于哪种类型。

{} instanceof Object; // true
// 无法区分
[] instanceof Array; // true
[] instanceof Object; // true
// 无法区分
new Date() instanceof Date; // true
new Date() instanceof Object; // true
// 无法区分
new Function() instanceof Function; // true
new Function() instanceof Object; // true
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值