JavaScript 数据类型

96 阅读2分钟

基本数据类型:字符串类型(string)、数值类型(number)(非数值NaN)、布尔类型(boolean)、未定义类型(undefined)、空类型(null)、symbol类型(ES6)。

引用数据类型:对象类型(object)。

1、获取数据类型

(1)typeof

console.log(typeof "hu");//打印结果:string
console.log(typeof 20);//打印结果:number
console.log(typeof true);//打印结果:boolean
console.log(typeof undefined);//打印结果:undefined
console.log(typeof null);//打印结果:object
console.log(typeof { age: 20 });//打印结果:object
console.log(typeof function(){});//打印结果:function

(2)instanceof 需要指定要判断的数据类型,反回布尔值(true or false),用来判断对象(object)是否为一个类。

let arr = [1,2,3];
let obj = { age:20 };
console.log(arr instanceof Array);//打印结果:true
console.log(arr instanceof Object);//打印结果:true,因为数组属于 object 类型派生出来的一种特殊类型。
console.log(obj instanceof Array);//打印结果:false
console.log(obj instanceof Object);//打印结果:true

(3)Object.prototype.toString.call() 原型方法。

console.log(Object.prototype.toString.call(null));//打印结果:[object Null]
console.log(Object.prototype.toString.call(undefined)); //打印结果:[object Undefined]
console.log(Object.prototype.toString.call(true)); //打印结果:[object Boolean]
console.log(Object.prototype.toString.call('hu'));//打印结果:[object String]
console.log(Object.prototype.toString.call(20));//打印结果:[object Number]
console.log(Object.prototype.toString.call(function(){}));//打印结果:[object Function]
console.log(Object.prototype.toString.call([1,2,3]));//打印结果:[object Array]
console.log(Object.prototype.toString.call({age:20}));//打印结果:[object Object]
console.log(Object.prototype.toString.call(new Date));//打印结果:[object Date]

2、类型转换

(1)字符串类型转换,除空类型(null)和未定义类型(undefined)外每种数据类型都具有一个toString()对象方法。

let num = 20;
let bool = true;
consolse.log(typeof num.toString());//打印结果:string
consolse.log(typeof bool.toString());//打印结果:string

(2)数值类型转换,Number()、parseInt()、parseFloat()。

参数类型参  数  值转     换
booleantruefalse10
number返回相同的值
nullnull0
undefinedundefinedNaN
string只包含数字返回对应数值
包含有效的浮点数返回对应浮点数
包含有效的十六进制数将十六进制数转换为十进制数并返回
包含有效的八进制数将八进制数转换为十进制数并返回
字符串为空0
除以上格式外NaN
object一般为 NaN

(3)布尔类型转换,Boolean()。

数据类型转换为 true转换为 false
number非零数字0 和 NaN
string非空字符串空字符串
booleantruefalse
null永远转换为 false
undefined
object任何对象(包括空对象)null