js 三种判断变量的方法

101 阅读1分钟

三种判断

1.typeof运算符

2.instanceof运算符

3.Object.prototype.toString方法

JS数据类型

基本数据类型

number boolean string null undefined Symbol

引用类型

1.Object Array Function

2.Boolean String Number NaN Infinity

2.Date RegExp Error

typeof

用来判断基本数据类型

typeof 124 // 'number'
typeof true // 'boolean'
typeof '12' // 'string'
typeof null // 'object'
typeof undefined // 'undefined' 
const a = Symbol('a') 
typeof a // 'symbol'

注意:typeof 判断null的时候是'object'

typeof null // 'object'

用来判断引用类型

typeof [] // 'object'
typeof {} // 'object'

typeof f() {} //  SyntaxError: Unexpected token '{' 
 
const f = function() {}
typeof f //  'function'

注意: typeof 用在func 是function, 而并非全是'object'

instanceof

a instanceof b: 判断b是否在a的原型链上

[] instanceof Array // true

{a: 123} instanceof Object  // Unexpected token 'instanceof'
function(){} instanceof Function //  SyntaxError: Function statements require a function name
function a() {} instanceof Function // SyntaxError: Unexpected token 'instanceof'

Symbol('a') instanceof Symbol // true