js判断数据类型及转换

基本类型

typeof

typeof 可以判断基本数据类型,返回值类型为字符串

基本类型 返回值
Boolean "boolean"
Number "number"
String "string"
Undefined "undefined"
Null "object"
Symbol "symbol"
typeof true === 'boolean'
typeof 1 === 'number'
typeof "a" === 'string'
typeof undefined === 'undefined'
typeof null === 'object'
typeof Symbol() === 'symbol'
引用类型 typeof 返回值
Function "function"
其他类型对象 "object"
typeof function(){} === 'function'
typeof {a:1} === 'object'

引用类型

instanceof

instanceof 可以判断引用数据类型,返回值类型为布尔值

引用类型 示例
Function function(){} instanceof Function
Array [] instanceof Array
Date new Date() instanceof Date
RegExp new RegExp('^http://') instanceof RegExp
Object {} instanceof Object

Array.isArray()

Array.isArray() 可以判断数组,返回值类型为布尔值

通用方法

Object.prototype.toString.call()

Object.prototype.toString.call() 可以判断所有数据类型,返回[object constructorName]格式的字符串

基本类型 返回值
Boolean "[object Boolean]"
Number "[object Number]"
String "[object String]"
Undefined "[object Undefined]"
Null "[object Null]"
Symbol "[object Symbol]"
Object.prototype.toString.call(true) === "[object Boolean]"
Object.prototype.toString.call(1) === "[object Number]"
Object.prototype.toString.call("a") === "[object String]"
Object.prototype.toString.call(undefined) === "[object Undefined]" 
Object.prototype.toString.call(null) === "[object Null]"
Object.prototype.toString.call(Symbol()) === "[object Symbol]"
引用类型 返回值
Function "[object Function]"
Array "[object Array]"
Date "[object Date]"
RegExp "[object RegExp]"
Object "[object Object]"
Object.prototype.toString.call(function(){}) === "[object Function]"
Object.prototype.toString.call([]) === "[object Array]"
Object.prototype.toString.call(new Date()) === "[object Date]"
Object.prototype.toString.call(new RegExp('^http://')) === "[object RegExp]"
Object.prototype.toString.call({}) === "[object Object]" 

类型转换

字符串转数字

1、parseInt()parseFloat()
语法:parseInt(string, radix)
string:要被解析的字符串;
radix:表示要解析的数字的基数。该值介于 2 ~ 36 之间。

parseInt("10");         //返回 10
parseInt("19",10);      //返回 19 (10+9)
parseInt("11",2);       //返回 3 (2+1)
parseInt("17",8);       //返回 15 (8+7)
parseInt("1f",16);      //返回 31 (16+15)
parseInt("010");        //未定:返回 10 或 8

2、+

let strType = "10";
let numType = +strType; // 10

数字转字符串

1、toString()
语法:number.toString(radix)
radix:规定表示数字的基数,是 2 ~ 36 之间的整数。

var num = 15;
var a = num.toString(); // 15
var b = num.toString(2); // 1111
var c = num.toString(8); // 17
var d = num.toString(16); // f

2、+拼接字符串

let numType = 10;
let strType = numType + "" ; // "10"

其他类型转布尔值

除了undefined、null、0、-0、NaN、''会被转换成false,其他的值都会转换成true。
1、Boolean()

let a = Boolean(null); // false

2、!!
负负得正,第一个转为相反的布尔值,第二个转回原本的布尔值。

let a = !!null; // false

文档

typeof
instanceof

网站导航

网站导航

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。