JS基础11-1强制类型转换String
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,minimal-ui:ios"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href=""> <script src=""></script> </head> <script> /** * 强制类型转换: * 指将一个数据类型强制转换为其他数据类型 * 主要是指将其他数据类型转换成:String,Number,Boolean类型 * **/ /* 将其他类型转换为String 方式一:调用被转换数据类型的toSting()方法 该方法不会影响原变量,会将转换的结果返回。 但是要注意null和undefined没有toString()方法,如果调用他们的方法会报错 方式二:调用String()函数 并将被转的数据作为参数传递给String()函数 该方法不会影响原变量,会将转换的结果返回。 使用String()函数做类型转换时: 对于Number和Boolean类型来说实际上就是调用了toString()方法 但是对于null和undefined就不会调用toString(),会将null直接转换为“null”将undefined直接转换为“undefined” 方式三:使用+拼接一个空字符串'' */ const a = 123 const b = a.toString()//定义变量接收 //a = a.toString()//用原变量接收 const c = true const d = c.toString() // var e = null // e = e.toString() // var f = undefined // f = f.toString() console.log(typeof (a)) console.log(a) console.log(typeof (b)) console.log(b) console.log(typeof (d)) console.log(d) // console.log(typeof (e)) // console.log(e) // console.log(typeof (f)) // console.log(f) /* 调用String函数 */ const a2 = 123 const b2 = String(a2)//定义变量接收 console.log(typeof (b2), b2) const c2 = true const d2 = String(c2) console.log(typeof (d2), d2) var e2 = null e2 = String(e2) console.log(typeof (e2), e2) var f2 = undefined f2 = String(f2) console.log(typeof (f2), f2) /* 使用+拼接一个空字符串'' */ const a3 = 123 const b3 = a3 + ''//定义变量接收 console.log(typeof (b3), b3) const c3 = true const d3 = c3 + '' console.log(typeof (d3), d3) var e3 = null e3 = e3 +'' console.log(typeof (e3), e3) var f3 = undefined f3 = f3 + '' console.log(typeof (f3), f3) </script> </html>