《编写可维护的JavaScript》- 类型检测

变量不与null比较

function process(items){
  if(items !== null){
  }
}

items可能是1或字符串甚至是对象,这些值都与null不相等
但有一个例外,就是期望值真的是null的时候

var element = document.getElementById('myDiv');
if(element !== null){
}

若DOM元素不存在,则通过document.getElementById()得到的值为null

检测原始值

JS中有5种原始类型:number、string、boolean、undefined和null
检测原始类型最佳选择是使用typeof,分别会返回字符串类型的“number”、“string”、“boolean”、“undefined”
不推荐typeof检测null,因为typeof null为“object”
typeof就算用于一个未定义的变量也不会报错,未定义或值为undefined都会返回“undefined”

检测引用类型

引用值也称为对象,JS中除了原始类型其他的值都是引用,内置的引用类型有Object、Array、Date和Error
使用typeof检测这些引用类型返回的都是“object”

检测引用类型最好的方法是使用instanceof运算符
instanceof不但会检测构造这个对象的构造器,也会检测原型链

原文地址:https://www.cnblogs.com/Grani/p/11355565.html