JavaScript 的数据类型:字符串、数字、布尔、数组、对象、Null、Undefined
ECMAScript 有 5 种原始类型(primitive type),即 Undefined、Null、Boolean、Number 和 String。
ECMAScript 引用类型通常叫做类(class),也就是说,遇到引用值,所处理的就是对象。
typeof、instanceof和constructor都可以用于识别正在处理的对象的类型。
typeof:
对变量或值调用 typeof 运算符将返回下列值之一:
- undefined - 如果变量是 Undefined 类型的
- boolean - 如果变量是 Boolean 类型的
- number - 如果变量是 Number 类型的
- string - 如果变量是 String 类型的
- object - 如果变量是一种引用类型或 Null 类型的
在使用 typeof 运算符时采用引用类型存储值会出现一个问题,无论引用的是什么类型的对象,它都返回 "object"。
ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。
instanceof
与 typeof 方法不同的是,instanceof 方法要求明确地确认对象为某特定类型。
constructor
constructor 属性返回对创建此对象的数组函数的引用。
constructor 可以是函数的,也可以是对象的,不过都是指向函数的一个引用。
一般函数定义的时候,默认有一个属性prototype.constructor
prototype
prototype 永远只属于函数,每个函数定义的时候,会默认有一个prototype。
判断数组:Object.prototype.toString.call(array) == '[object Array]'
例子:
var xx = "good" ;
typeof xx ;// string
xx instanceof Stirng //false ,注意instance 只对用new生成(对象)的才有效
xx.constructor == String //true
xx.constructor.prototype.constructor == String //true
var xx =new Array(11,12,13) ;
typeof xx ;//object
xx instanceof Array //true
xx.constructor == Array //true
xx.constructor.prototype.constructor == Array //true
xx instanceof Object //true
xx.constructor == Object //false
xx.constructor.prototype.constructor == Object //false
一篇讲javascript判断变量比较好的文章:http://web.jobbole.com/82609/