数据类型
1.基本类型(5种)
Number 数字类型 1 2 3 4
String 字符串类型 '123'
Boolean 布尔类型 true false
undefined 未定义的值 1.声明变量但没有赋值 2.访问对象上不存在或者未定义的值 3.函数定义了形参,没有传递实参 4.使用void对表达式求值
null 空值 表示一个空引用的特殊值
2.引用数据类型
object array function
注: array和function本质上是object
array 为有序的对象、数值下标
function 为可执行的对象
判断数据类型方法:
var a = 1, b = '1', c = true, d
var obj= {
a: [1, 2, console.log],
b: function(name) {
return name
}
}
1. typeof
返回值为小写字符串 可以判断 number string boolean undefined funciton
typeof a // 'number'
typeof b // 'string'
typeof c // 'boolean'
typeof d // 'undefined'
typeof obj.b // 'function'
**注:**
typeof null // 'object' 实际上返回object可以算是js的一个bug
typeof [] // 'object'
typeof {} // 'object'
2. instanceof
可以判断引用数据类型 object array function
console.log(obj instanceof Object) // true
console.log(obj.a instanceof Array) // true
console.log(obj.a instanceof Object) // true 前面讲到了array为特殊类型的对象
console.log(obj.b instanceof Function) // true 同理function也是特殊类型的对象
**注:**
console.log(null instanceof Objcet) // false
3. ===
可以判断unll和undefined
console.log(null === null) // true
console.log(undefined === undefined) // true
思考?
利用typeof、instanceof和===写一个方法来实现判断所传入参数的类型