1、typeof
返回一个变量的基本类型,用来检测值类型的数据类型,只有以下几种:
number,boolean,string,object,undefined,function
alert(typeof 1) //number
alert(typeof "1") //string
alert(typeof []) //object
alert(typeof null) //object
alert(typeof a) //undefined
2、instanceof
返回的是一个布尔值,用来判断对象和函数,不能用来判断字符串和数字等
var a={};
alert(a instanceof Object); //true
var b=[];
alert(b instanceof Array); //true
alert("string" instanceof String); //false
alert(new String("string")instanceof String); //true
3、Object.prototype.toString
用来精确判断对象的类型
alert(Object.prototype.toString.call([])) // "[object Array]"
Object.prototype.toString.call({}) //"[object Object]"
Object.prototype.toString.call(new Date()) //"[object Date]"
本文介绍了JavaScript中三种常用类型检测方法:typeof操作符、instanceof关键字和Object.prototype.toString方法。typeof可以检测基本数据类型,instanceof用于判断对象实例,而Object.prototype.toString则能更精确地确定对象的具体类型。
1295

被折叠的 条评论
为什么被折叠?



