数据类型js 基本类型包括:Undefined symbol null string boolean numberjs 引用类型包括:object array Date RegExp typeof我们一般用typeof来判断数据的类型的接下来我们试试cons ...
数据类型
js 基本类型包括:Undefined symbol null string boolean number
js 引用类型包括:object array Date RegExp
typeof
我们一般用typeof来判断数据的类型的
接下来我们试试
console.log(typeof undefined) //undefinedconsole.log(typeof null) //objectconsole.log(typeof Undefined) //undefinedconsole.log(typeof Null) //undefinedconsole.log(typeof '123') //stringconsole.log(typeof 123) //numberconsole.log(typeof true) //booleanconsole.log(typeof {a:123}) //objectconsole.log(typeof (new Date)) //objectconsole.log(typeof function(){}) //functionconsole.log(typeof Infinity) //numberconsole.log(typeof NaN) //numberconsole.log(typeof Number(1)) //numberconsole.log(typeof Symbol('foo')) //symbolconsole.log(typeof Symbol()) //symbolconsole.log(typeof [1,2,3]) //object</script>
typeof 是一个操作符,主要的目的是检测一个变量是不是基本数据类型的变量,同时也可以说是确定一个变量是字符串,数值,布尔值,还是undefined
的最佳工具。
上面很明显对于引用类型的判断只返回object,并不能反应是哪种数据类型
这样就引出了另一个判断数据类型的方法
Object.prototype.toString
console.log(Object.prototype.toString.call("jerry"));//[object String]console.log(Object.prototype.toString.call(12));//[object Number]console.log(Object.prototype.toString.call(true));//[object Boolean]console.log(Object.prototype.toString.call(undefined));//[object Undefined]console.log(Object.prototype.toString.call(null));//[object Null]console.log(Object.prototype.toString.call({name: "jerry"}));//[object Object]console.log(Object.prototype.toString.call(function(){}));//[object Function]console.log(Object.prototype.toString.call([]));//[object Array]console.log(Object.prototype.toString.call(new Date));//[object Date]console.log(Object.prototype.toString.call(/\d/));//[object RegExp]function Person(){};console.log(Object.prototype.toString.call(new Person));//[object Object]
instanceof
instanceof 就是判断一个实例是否属于某种类型
// 判断 foo 是否是 Foo 类的实例function Foo(){} var foo = new Foo(); console.log(foo instanceof Foo)//true
还有一些特殊的
console.log(Object instanceof Object);//true console.log(Function instanceof Function);//true console.log(Number instanceof Number);//false console.log(String instanceof String);//false console.log(Function instanceof Object);//true console.log(Foo instanceof Function);//true console.log(Foo instanceof Foo);//false
这个知识点就和原型链,具体请看
-->
原标题:typeof 、Object.prototype.toString和 instanceof
关键词:string
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。