数据类型

js 基本类型包括:Undefined  symbol null string boolean number

js 引用类型包括:object array Date RegExp


 

typeof

我们一般用typeof来判断数据的类型的

接下来我们试试

console.log(typeof undefined)  //undefined

console.log(typeof Undefined) //undefined
console.log(typeof Null)         //undefined
console.log(typeof null)          //object
console.log(typeof '123')         //string
console.log(typeof 123)           //number
console.log(typeof true)          //boolean
console.log(typeof {a:123})    //object
console.log(typeof (new Date))   //object
console.log(typeof function(){})   //function
console.log(typeof Infinity)      //number
console.log(typeof NaN)          //number
console.log(typeof Number(1))  //number
console.log(typeof Symbol('foo'))    //symbol
console.log(typeof Symbol())        //symbol
console.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]

obj.toString()的结果和Object.prototype.toString.call(obj)的结果不一样,这是为什么?

     这是因为toString为Object的原型方法,而Array 、Function等类型作为Object的实例,都重写了toString方法

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

这个知识点就和原型链,具体请看

http://www.cnblogs.com/wangfupeng1988/p/3977987.html

 

posted on 2017-09-06 18:25  坚持不懈❥  阅读(258)  评论(0编辑  收藏  举报