JavaScript中5种方法检测变量类型

JavaScript检测变量类型的方法1.typeof 2.instanceof 3.constructor 4.Object.prototype.toString.call() 5.jquery的$.type等。

这里介绍最简单方便的typeof

<script type="text/javascript">
    function fn(obj){
        return typeof(obj)=="string";
        //js检测一个变量是一个String类型
    }
    document.write(fn("hello"));
</script>

<script type="text/javascript">
	var num  = 123;
	var str  = 'abcdef';
	var bool = true;
	var arr  = [1, 2, 3, 4];
	var json = {name:'cz', age:21};
	var func = function(){ console.log('this is function'); }
	var und  = undefined;
	var nul  = null;
	var date = new Date();
	var reg  = /^[a-zA-Z]{5,20}$/;
	var error= new Error();
	document.write(
	    typeof num,
	    '\t',
	    typeof str,
	    '\t',
	    typeof bool,
	    '\t',
	    typeof arr,
	    '\t',
	    typeof json,
	    '\t',
	    typeof func,
	    '\t',
	    typeof und,
	    '\t',
	    typeof nul,
	    '\t',
	    typeof date,
	    '\t',
	    typeof reg,
	    '\t',
	    typeof error
	);
</script>

截图:

typeof 优点:使用简单,直接输出结果 缺点:可检测类型太少,无法检测object对象的类型

其他四种方法请了解这两篇文章,更详细。

https://blog.csdn.net/qq_39159168/article/details/78294508

https://www.cnblogs.com/zhangruiqi/p/8027338.html

猜你喜欢

转载自blog.csdn.net/Cai181191/article/details/82716448