JS类型操作简单总结

最近项目中遇到一些JS类型判断和转换的问题,在这里简单总结一下。不定期更新此文。

类型操作

  • 类型检测优先使用 typeof。
  • 对象类型检测使用 instanceof。
  • null 或 undefined的检测使用 == null。(注意:typeof null 是 object)
typeof a === 'string'

  

typeof a === 'number'

typeof a === 'boolean' 

typeof a === 'function'

typeof a === 'object' 

 

a instanceof RegExp // RegExp
a instanceof Array // Array
a === null // null
a == null // null or undefined
typeof a === 'undefined' // undefined

  

类型的快速转换

    • Number转换成String可以直接在后面加单引号

    • String转成Number可以在前面加+

    • String 转Number时候如果要转换的字符串结尾包含非数字时,可以用parseInt,使用parseInt时一定注意指定进制
var b = '100px';
parseInt(b, 10); // output 100
    • 转换成 Boolean 时,使用 !!

    • Number去除小数点,用 Math.floor,Math.round, Math.ceil,不用parseInt方法

 

 

 

  

 

posted on 2017-11-27 14:50  掌上名猪  阅读(81)  评论(0)    收藏  举报

导航