数据类型
- 布尔值(Boolean) : ture和false
- 数值(number) : 整数和小数
- 字符串(string) : 文本
- undefined : 表示目前无定义,暂时没有任何值
- null : 表示空值
- 对象 (object) : 各种数据类型,函数和值所组成的集合
布尔值,字符串和数值为原始类型的值,即为最基本的数据类型,对象为多个原始类型的值的合成,可看作存放各种值的容器。undefined和null为两个特殊值,可单独记忆。
对象是最复杂的数据类型,可再分为三个子类型
- 狭义对象(object)
- 数组(array)
- 函数(function) : 涵数其实是处理数据的方法,JS把它当作一种数据类型,可赋值给变量。
判断数据类型的方法
- typeof 运算符
- instanceof 运算符
- Object.prototype.toString 方法
typeof运算符
数值、字符串、布尔值分别返回 number、string、boolean。
typeof 153 //"number" typeof '345' // "string" typeof true // "boolean"
函数返回 function
function f (){}
typeof f //"function"
undefined 返回 undefined
typeof undefined // "undefinde"
对象返回 object
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
instenceof 运算符
instenceof 运算符 检测某个构造函数的prototype属性是否在另一个需要检测对象的原型链上
实例一:普遍用法
A instanceof B :检测B.prototype是否存在于参数A的原型链上.
function Ben() {
}
var ben = new Ben();
console.log(ben instanceof Ben);//true
实例二:继承中判断实例是否属于它的父类
function Ben_parent() {}
function Ben_son() {}
Ben_son.prototype = new Ben_parent();//原型继承
var ben_son = new Ben_son();
console.log(ben_son instanceof Ben_son);//true
console.log(ben_son instanceof Ben_parent);//true
实例三:表明String对象和Date对象都属于Object类型
下面的代码使用了instanceof来证明:String和Date对象同时也属于Object类型。
var simpleStr = "This is a simple string";
var myString = new String();
var newStr = new String("String created with constructor");
var myDate = new Date();
var myObj = {};
simpleStr instanceof String; // returns false, 检查原型链会找到 undefined
myString instanceof String; // returns true
newStr instanceof String; // returns true
myString instanceof Object; // returns true
myObj instanceof Object; // returns true, despite an undefined prototype
({}) instanceof Object; // returns true, 同上
myString instanceof Date; // returns false
myDate instanceof Date; // returns true
myDate instanceof Object; // returns true
myDate instanceof String; // returns false
实例四:演示mycar属于Car类型的同时又属于Object类型
下面的代码创建了一个类型Car,以及该类型的对象实例mycar. instanceof运算符表明了这个mycar对象既属于Car类型,又属于Object类型。
function Car(make, model, year)
{
this.make = make;
this.model = model;
this.year = year;
}
var mycar = new Car("Honda", "Accord", 1998);
var a = mycar instanceof Car; // 返回 true
var b = mycar instanceof Object; // 返回 true