如何判断该变量存放的值是什么类型的?

typeof 运算符

typeof 是一元运算符,放在其单个操作数的前面,操作数可以是任意类型。返回值为表示操作数类型的一个字符串。

typeof undefined === "undefined"; // true
typeof true === "boolean"; // true
typeof 45 === "number";  //true
typeof "45" === "string"; // true
typeof {life: 42} === "object"; //true
typeof Symbol() === "symbol"; // true, ES6中新加入的类型

以上6种数据类型均有同名的字符串与之对应,但有几个特殊的如下:

typeof null === "object"; // true

正确的返回结果应该是 “null”,但这个bug存在时间太久了,在JavaScript中已经存在20年左右,也许永远都不会修复,因为这牵涉到太多的web系统,“修复”它会产生更多的bug,令许多系统都无法正常工作。

还有一种情况:

typeof function a(){ /*   */} === "function"; // true

函数实际上是 object 的一个"子类型"。具体来说函数是“可调用对象”,它有一个内部属性 [[Call]], 该属性使其可以被调用。
函数不仅是对象,还可以拥有属性。例如:

function a(b, c){
	/* .. */ 
}

函数对象的 length 属性是其声明的参数的个数:

a.length; // 2

猜你喜欢

转载自blog.csdn.net/xiebinyin/article/details/92393349