四种判断数据类型的方法

编程入门 行业动态 更新时间:2024-10-28 02:30:35

1.typeof

typeof undefined 	// 'undefined' 
typeof '10' 		// 'string' 
typeof 10 			// 'number' 
typeof false 		// 'boolean' 
typeof Symbol() 	// 'symbol' 
typeof Function 	// ‘function' 
typeof null 		// ‘object’ 
typeof [] 			// 'object' 
typeof {} 			// 'object'

缺点:
(1)typeof null的结果为object,无法分辨是null还是object
(2)typeof 数组 的结果始终为object

2.instanceof

function Func() { }
var func = new Func();
var n = new Number(1)console.log(func instanceof Func);// true
console.log(n instanceof Number); //true
console.log(12 instanceof Number); //false   -->不能判断字面量的基本数据类

缺点:只能判断对象是否存在于目标对象的原型链上,不能判断基本数据类型

3.constructor

var a = 1;
var b = new Number(1);
function func(){console.log("haha");
}
func.prototype = new Array();
var func2 = new func();
var date = new Date();
var arr = [1,2,3];
var reg = /"ex"/gi;console.log(a.constructor);		//f Number {[native code]}
console.log(b.constructor);		//f Number {[native code]}console.log(func.constructor);	//f Function {[native code]}
console.log(func2.constructor)	//f Array() {[native code]}console.log(date.constructor);	//f Date {[native code]}
console.log(arr.constructor);	//f Array {[native code]}
console.log(reg.constructor);	//f RegExp {[native code]}

4.Object.prototype.toString.call()

console.log(Object.prototype.toString.call(undefined)); // "[object Undefined]" 
console.log(Object.prototype.toString.call(null)); // "[object Null]" 
console.log(Object.prototype.toString.call(123)); // "[object Number]" 
console.log(Object.prototype.toString.call("abc")); // "[object String]" 
console.log(Object.prototype.toString.call(true)); // "[object Boolean]" function fn() {console.log("ming");
}
var date = new Date();
var arr = [1, 2, 3];
var reg = /[hbc]at/gi;
console.log(Object.prototype.toString.call(fn));// "[object Function]" 
console.log(Object.prototype.toString.call(date));// "[object Date]" 
console.log(Object.prototype.toString.call(arr)); // "[object Array]"
console.log(Object.prototype.toString.call(reg));// "[object RegExp]"

最好的基本类型检测方式 Object.prototype.toString.call() ;它可以区分 null 、 string
boolean 、 number 、 undefined 、 array 、 function 、 object 、 date 、 math 数据类型

更多推荐

四种,数据类型,方法

本文发布于:2023-05-26 18:04:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/275009.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:四种   数据类型   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!