◆
JavaScript typeof 操作符返回值详解
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';
tip
最初的 JavaScript 语言第一版,只设计了五种数据类型(对象、整数、浮点数、字符串和布尔值),没考虑 null,只把它当作 object 的一种特殊值。后来 null 独立出来,作为一种单独的数据类型, 为了兼容以前的代码,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'
tip
es6 之前 typeof 总能保证对任何所给的操作数返回一个字符串。即便是没有声明的标识符,typeof 也能返回 undefined。 es6 加入了块级作用域的 let 和 const 之后,在其被声明之前对块中的 let 和 const 变量使用 typeof 会抛出一个 ReferenceError。
typeof newConstVariable; // ReferenceError
const newConstVariable = 'hello';

还没有留言,来发表第一条吧~