您的位置:首页 > 移动开发 > Objective-C

判断变量的类型(typeof、instanceof、Object.prototype.toString)

2017-09-06 14:23 477 查看
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]"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: