js类型判断

发布时间:2022-07-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了js类型判断脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

判断数组

let arr = []

Array.isArray(arr)
// true

arr.constructor === Array
// true

Object.PRototyPE.toString.call(arr)
// "[object Array]"

typeof 判断对象或者数组或者null都为"object" 

判断对象

let obj = {}

Object.prototype.toString.call(obj)
// "[object Object]"

obj.constructor === Object
// true

instanceof  判断对象和数组都为true

判断函数

function fn(){
	console.LOG('hello world')
}

Object.prototype.toString.call(fn)
// "[object Function]"

不同数据类型的Object.prototype.toString方法返回值如下。

数值:返回[object Number]。
字符串:返回[object String]。
布尔值:返回[object Boolean]。
undefined:返回[object Undefined]。
null:返回[object Null]。
数组:返回[object Array]。
arguments 对象:返回[object arguments]。
函数:返回[object Function]。
Error 对象:返回[object Error]。
Date 对象:返回[object Date]。
RegExp 对象:返回[object RegExp]。
其他对象:返回[object Object]。

扩展数据类型判断函数

function myTypeOf(v){
	VAR str = Object.prototype.toString.call(v);
	var reg = /[object (.*?)]/;
	return str.match(reg)[1].toLowerCase();
}

myTypeOf({});
// "object"

myTypeOf([]);
// "array"

myTypeOf(myTypeOf);
// "function"

myTypeOf(null);
// "null"

myTypeOf('abc');
// "string"

myTypeOf(/reg/);
// "regexp"

myTypeOf();
// "undefined"

脚本宝典总结

以上是脚本宝典为你收集整理的js类型判断全部内容,希望文章能够帮你解决js类型判断所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。