javascript - 判断变量类型type

#数据类型

最常见的判断方法:typeof

1
2
3
4
5
6
7
8
9
10
11
// 可以区分基本类型和undefined
typeof '123' // 'string'
typeof 123 // 'number'
typeof true // 'boolean'
typeof function test(){} // 'function'
typeof undefined // 'undefined'

// 对象类型无法区分
typeof {} // 'object'
typeof [] // 'object'
typeof null // 'object'

判断已知对象类型的方法: instanceof

  • null的typeof为object,function和undefined可以使用typeof
1
2
3
4
5
# 可以区分object和array分别是哪个构造函数的实例
{} instanceof Object // true
[] instanceof Array// true
test instanceof Function// true
new Date() instanceof Date// true

prototype

1
2
3
4
5
6
alert(Object.prototype.toString.call(‘123’) === ‘[object String]’) -------> true;
alert(Object.prototype.toString.call(123) === ‘[object Number]’) -------> true;
alert(Object.prototype.toString.call([]) === ‘[object Array]’) -------> true;
alert(Object.prototype.toString.call(new Date()) === ‘[object Date]’) -------> true;
alert(Object.prototype.toString.call(test) === ‘[object Function]’) -------> true;
alert(Object.prototype.toString.call(null) === ‘[object Null]’) -------> true;

##基本类型

String

typeof // “string”

Number

typeof // ‘number’

Boolean

typeof boolean // ‘boolean’

特殊类型

null

typeof // 注意是‘object’

undefined

typeof // ‘undefined’

function

function test(){}
typeof test // ‘function’

##变态类型
object
typeof // object
instantceof Object // true
function
typeof // function
instance of Function // true
array
typeof //object
instance of Array // true

初到贵宝地,有钱的给个钱场,没钱的挤一挤给个钱场