js中判断变量为某一类型

93 阅读1分钟

本文总结一下在js中,需要判断变量为某一类型,(基本都可以用typeof 判断,null除外)以下示例都以'test_val'做为变量名

判断为null

if (test_val === null) {}

相关知识:

typeof null        // "object" (因为一些以前的原因而不是'null',比较特殊)
typeof undefined    //"undefined"
null === undefined // false
null  == undefined // true
null === null // true
null == null // true
1 + null = 1 //null进行数学运算时转为0
1 + undefined = NaN

判断为undefined

if (typeof test_val === 'undefined') {} //不直接使用test_val === undefined