javascript之typeof

mac2022-06-30  30

定义和用法

?typeof操作符返回一个字符串,表示未经计算的操作数的类型。

参数: 是一个表达式,表示对象或原始值,其类型将被返回。括号是可选的。 返回值:

类型结果Undefined"undefined"Null"object"Boolean"boolean"Number"number"String"string"Symbol"symbol"宿主对象(由JS环境提供)Implementation-dependent函数对象([[Call]] 在ECMA-262条款中实现了)"function"任何其他对象"object"

DEMO

// Numbers typeof 37 === 'number'; typeof 3.14 === 'number'; typeof Math.LN2 === 'number'; typeof Infinity === 'number'; typeof NaN === 'number'; // 尽管NaN是"Not-A-Number"的缩写 typeof Number(1) === 'number'; // 但不要使用这种形式! // Strings typeof "" === 'string'; typeof "bla" === 'string'; typeof (typeof 1) === 'string'; // typeof总是返回一个字符串 typeof String("abc") === 'string'; // 但不要使用这种形式! // Booleans typeof true === 'boolean'; typeof false === 'boolean'; typeof Boolean(true) === 'boolean'; // 但不要使用这种形式! // Symbols typeof Symbol() === 'symbol'; typeof Symbol('foo') === 'symbol'; typeof Symbol.iterator === 'symbol'; // Undefined typeof undefined === 'undefined'; typeof declaredButUndefinedVariable === 'undefined'; typeof undeclaredVariable === 'undefined'; // Objects typeof {a:1} === 'object'; // 使用Array.isArray 或者 Object.prototype.toString.call // 区分数组,普通对象 typeof [1, 2, 4] === 'object'; typeof new Date() === 'object'; // 下面的容易令人迷惑,不要使用! typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String("abc") === 'object'; // 函数 typeof function(){} === 'function'; typeof class C{} === 'function' typeof Math.sin === 'function'; typeof new Function() === 'function'; typeof null === 'object'; // 从一开始出现JavaScript就是这样的

总结:

1.typeof 对于基本类型,除了 null 都可以显示正确的类型 2.typeof 对于对象,除了函数都会显示 object 3.对于 null 来说,虽然它是基本类型,但是会显示 object,这是一个存在很久了的 Bug

PS: JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 null 代表的是空指针(大多数平台下值为 0x00),因此,null的类型标签也成为了 0,typeof null就错误的返回了"object"。ECMAScript提出了一个修复(通过opt-in),但被拒绝。这将导致typeof null === 'null'。

如果我们想获得一个变量的正确类型,可以通过 Object.prototype.toString.call(xx)。这样我们就可以获得类似 [object Type] 的字符串。

let a // 我们也可以这样判断 undefined a === undefined // 但是 undefined 不是保留字,能够在低版本浏览器被赋值 let undefined = 1 // 这样判断就会出错 // 所以可以用下面的方式来判断,并且代码量更少 // 因为 void 后面随便跟上一个组成表达式 // 返回就是 undefined a === void 0

转载于:https://www.cnblogs.com/guangzan/p/11270660.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)