JS基礎11-2強制型別轉換Number
阿新 • • 發佈:2022-11-29
<!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> /* 將其他型別轉換為Number 轉換方式一: 使用Number()函式,使用方式與Sting()函式相同 1.如果是純數字的字串,則直接將其轉換為數字 2.如果字串中有非數字的內容則轉換為NAN(NOT A NUMBENR) 3.如果字串是空字串或者是一個全是空格的字串則轉換為0 布林 --》數字:true轉換為1;false轉換為0; null --》數字:null轉為數字是0 undefined --》數字:undefined轉為數字是NAN 轉換方式二: 這種方式專門用來轉換字串 paseInt()把一個字串轉換為整數 paseInt()方法把一個字串中有效的整數內容取出來轉換為了Number,注:遇到第一個不是整數的字元後就會不在往下找 paseFloat()把一個字串轉換為浮點數 paseFloat()方法把一個字串中有效的浮點數內容取出來轉換為了Number,注:遇到第一個不是浮點數的字元後就會不在往下找 如果對非String型別使用parseInt()或者parseFloat()方法 會先將其轉換為String,parseInt()方法來取整 */ /* 使用Number()函式轉換 */ var a = '123' a = Number(a)//123 console.log(typeof (a), a) var b = true b = Number(b)//1 console.log(typeof (b), b) var c = null c = Number(c)//NAN console.log(typeof (c), c) var d = undefined d = Number(d)//NAN console.log(typeof (d), d) var e = 'abc' e = Number(e)//NAN console.log(typeof (e), e) var f = '1abc' f = Number(f)//NAN console.log(typeof (f), f) /* 使用parseInt()和parseFloat()函式轉換 */ a2 = '100px' a2 = parseInt(a2)//100 b2 = '-100px' b2 = parseInt(b2)//-100 d2 = 'ab100bc' d2 = parseInt(d2)//NAN c2 = '100.001px' c2 = parseFloat(c2)//100.001 e2 = '-100.001px' e2 = parseFloat(e2)//-100.001 g = 123.234 g = parseInt(g)//123 console.log(typeof (a2), a2) console.log(typeof (b2), b2) console.log(typeof (c2), c2) console.log(typeof (d2), d2) console.log(typeof (e2), e2) console.log(typeof (g), g) </script> </html>