天天看点

typeof返回值详解

typeof

 操作符返回一个字符串

typeof

 可能的返回值

类型 结果
Undefined undefined
Null object
Boolean boolean
Number number
BigInt bigint
String string
Symbol symbol
Function function
其他任何对象 object

number 

// 数值
typeof(42) === 'number';
typeof Math.LN2 === 'number';
typeof Infinity === 'number';
typeof NaN === 'number'; // 尽管它是 "Not-A-Number" (非数值) 的缩写
typeof Number(1) === 'number'; // Number 会尝试把参数解析成数值
           

bigint 

typeof 42n === 'bigint';
           

 string

// 字符串
typeof '' === 'string';
typeof `template literal` === 'string';
typeof '1' === 'string'; // 注意内容为数字的字符串仍是字符串
typeof (typeof 1) === 'string'; // typeof 总是返回一个字符串
typeof String(1) === 'string'; // String 将任意值转换为字符串,比 toString 更安全
           

 bollean

// 布尔值
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(1) === 'boolean'; // Boolean() 会基于参数是真值还是虚值进行转换
typeof !!(1) === 'boolean'; // 两次调用 ! (逻辑非) 操作符相当于 Boolean()
           

symbol 

// Symbols
typeof Symbol() === 'symbol';
typeof Symbol('foo') === 'symbol';
typeof Symbol.iterator === 'symbol';
           

undefined

// Undefined
typeof undefined === 'undefined';
typeof undeclaredVariable === 'undefined'; 
           

object

typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
typeof new Date() === 'object';
typeof /regex/ === 'object';
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
           

function

typeof function() {} === 'function';
typeof class C {} === 'function'
typeof Math.sin === 'function';
typeof console.log // 'function'
           

null:虽然 typeof null 会输出 object,但是这只是 JS 存在的一个悠久 Bug。在 JS 的最初版本中使用的是 32 位系统,为了性能考虑使用低位存储变量的类型信息,000 开头代表是对象然而 null 表示为全零,所以将它错误的判断为 object 。

typeof null === 'object';
           

除 Function 外的所有构造函数的类型都是 'object'

var str = new String('String');
var num = new Number(100);

typeof str; // 返回 'object'
typeof num; // 返回 'object'

var func = new Function();

typeof func; // 返回 'function'
           

语法中的括号

// 括号有无将决定表达式的类型。
var iData = 99;

typeof iData + ' Wisen'; // 'number Wisen'
typeof (iData + ' Wisen'); // 'string'
           

es6之前

typeof

 总能保证对任何所给的操作数返回一个字符串。即便是没有声明的标识符,

typeof

 也能返回 

'undefined'

es6加入了块级作用域的 let 和 const 之后,在其被声明之前对块中的 let 和 const 变量使用 typeof 会抛出一个 ReferenceError。

typeof newConstVariable; // ReferenceError
const newConstVariable = 'hello';
           

继续阅读