你不知道的javascript(中篇)

一、类型
1、(null类型的问题)

回顾typeof检测数据类型

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

以上六种类型均有同名的字符串值与之对应。
你可能注意到null类型不在此列。它比较特殊,typeof 对它的处理有问题:

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

正确的返回结果应该是"null",但这个bug由来已久,在JavaScript中已经存在了将近二十年,也许永远也不会修复,因为这牵涉到太多的Web系统,“修复”它会产生更多的bug,令许多系统无法正常工作。

我们需要使用复合条件来检测null值的类型:

var a = null;
(!a && typeof a === "object"); // true

null是基本类型中唯一的一个“假值”
(falsy或者false-like,typeof对它的返回值为"object")

2、function类型检测和长度检测

函数不仅是对象,还可以拥有属性。
例如:
function a(b,c) {
/* .
*/
}
函数对象的length属性是其声明的参数的个数:
a.length; // 2
因为该函数声明了两个命名参数,
b和c,所以其length值为2

3、undefined和undeclared
已在作用域中声明但还没有赋值的变量,是undefined的。相反,还没有在作用域中声明
过的变量,是undeclared的。
例如:

var a;
a; // undefined
b; // ReferenceError: b is not defined

浏览器处理未定义的变量

浏览器对这类情况的处理很让人抓狂。上例中,“b is not defined”容易让人误以为是“b is
undefined”。这里再强调一遍,“undefined”和“is not defined”是两码事。此时如果浏览器
报错成“b is not found”或者“b is not declared”会更准确。

typeof处理未定义变量

更让人抓狂的是typeof处理undeclared变量的方式。例如:

var a;
typeof a; // "undefined"
typeof b; // "undefined"

对于undeclared(或者not defined)变量,typeof照样返回"undefined"。请注意虽然b是一个undeclared变量,但typeof b并没有报错。这是因为typeof
有一个特殊的安全防范机制。此时typeof如果能返回undeclared(而非
undefined))的话,情况会好很多。

猜你喜欢

转载自blog.csdn.net/qq_44472790/article/details/119512986
今日推荐