JS复杂类型的了解
-
Array
:数组 -
Function
:函数 -
Object
:对象 -
Math
:处理数学运算的类型 -
Date
:处理日期时间的类型 -
RegExp
:处理正则表达式的类型 -
UUID
:处理唯一数据的类型
// 复杂类型的基本使用
// 日期
var date = new Date()
console.log("今年是:", date.getFullYear(), ",月份:", date.getMonth() + 1)
// 随机数:得到一个验证码
var rcode = Math.random().toString(36).substr(2, 6)
console.log("随机验证码:", rcode)
查看类型
-
typeof(dat)
:简易的数据类型查看方式,适用于大部分场景 -
Object.prototype.toString.call(dat)
:数据类型原型查看方式,有争议的情况下可以使用
// 定义基本类型
var name = "小明"
console.log(name, typeof name) // 小明 string
var hero = "小红"
console.log(hero, typeof(hero)) // 小红 string
var height = 20
console.log(height, typeof(height)) // 20 'number'
var pi = 3.1415
console.log(pi, typeof(pi)) // 3.1415 'number'
//........等
常见的类型转变
// 同一个数据,可以是不同的类型
// var n1 = 3.14 // number
// var n2 = '3.14' // string
// var b1 = true // boolean
// var b2 = 'false' // string
// 需要进行类型转换(大部分类型转换都是基本类型的转换)
// 将其他类型转换成字符串类型
var b = true
var b1 = String(b)
console.log(b1, typeof(b1)) // 'true' string
var n = null
var n1 = String(null)
console.log(n1, typeof(n1)) // 'null' string
var u = undefined
var u1 = String(u)
console.log(u1, typeof(u1)) // 'undefined' string
// 转换成数值
var age = '20.01'
console.log(age, typeof(age)) // '20' string
// 转换成数值
var a1 = Number(age)
console.log(a1, typeof(a1)) // 20.01 number
// 转换成整数
var a2 = parseInt(age)
console.log(a2, typeof(a2)) // 20 number
// 转化成浮点数
var a3 = parseFloat(age)
console.log(a3, typeof(a3)) // 20.01 number
// 其他类型
// 布尔类型,true -> 1;false -> 0
var b = true
var b1 = Number(b)
console.log(b1, typeof(b1)) // 1 number
显性/隐式的转换
// 通过固定语法,将类型进行转换后完成数据运算:显示类型转换
// 1.
var price = '20'
var total = price + price
var totalx = parseInt(price) + pasreInt(price) // 显式转换
console.log('total:', total) // total: 2020 期望以外的错误结果(代码没有报错)
// 数据的隐式类型转换:数据参与运算时,类型在运算过程中进行了自动匹配转换
// 2. 字符串和数值执行乘法运算时,出现了类型自动转换(字符串-> 数值-> 参与运算)
var price2 = '30'
var cnt = 2
var total2 = price2 * 2 // 字符串 乘以 数值
console.log('total2:', total2) // total2: 60
// 3. 字符串和字符串执行减法运算时,出现类型自动转换(字符串-> 数值-> 参与运算)
var pay = '180'
var money = '200'
var balance = money - pay // 字符串 减法 字符串
console.log("找零:", balance) // 找零: 20
总结:
显式类型转换,是开发人员通过固定的语法如parseInt()/parseFloat()/Number()..对目标数据进行指定类型转换的方式
隐式类型转换,是程序运行过程中,解释器执行数据运算时,自动匹配数据对应的类型
显式类型转换能提高代码的可读性;隐式类型转换简化代码的复杂度!