JavaScript中變數(shù)的幾個(gè)相關(guān)函數(shù)
判斷變數(shù)的資料型態(tài):
#typeof()
使用typeof(),可以測(cè)試一個(gè)變數(shù)的型別。
typeof()測(cè)試的結(jié)果是一個(gè)型別字串。
typeof()的結(jié)果字串有幾種狀況:?「string」?、「number」?、?「boolean」?、?「undefined」?、「object」?、?「function」
另外:null、物件、陣列這三種類型,都會(huì)傳回「object」。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var x1 = "abc"; //string var x2 = 110; //number var x3 = true; //boolean var x4; //undefined var x5 = null; //object //使用typeof()判斷變量的數(shù)據(jù)類型 var result = typeof(x5); //輸出變量的類型和結(jié)果 document.write(x5+"的數(shù)據(jù)類型為:"+result); </script> </head> <body> </body> </html>
註:大家可以嘗試判斷其他幾個(gè)變數(shù)的資料型別
從字串中提取整數(shù)和浮點(diǎn)數(shù)函數(shù)
#parseInt()系統(tǒng)函數(shù)、全域函數(shù)
功能:在一個(gè)字串中,從左往右提取整數(shù)。如果遇到非整型的內(nèi)容,則停止提取,並傳回結(jié)果。
註:如果第一個(gè)字元是非整數(shù),則立即停止,並傳回NaN。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> document.write(parseInt("500eps")+"<br/>"); document.write(parseInt("500.88")+"<br/>"); document.write(parseInt("a120px")+"<br/>"); </script> </head> <body> </body> </html>
parseFloat()系統(tǒng)函數(shù)、全域函數(shù)
功能:在一個(gè)字串中,從左往右提取浮點(diǎn)型;遇到非浮點(diǎn)型內(nèi)容,則停止提取,並返回結(jié)果。
註:如果第一個(gè)字元是非浮點(diǎn)型,則立即停止,並傳回NaN。
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> document.write(parseFloat("500eps")+"<br/>"); document.write(parseFloat("500.88")+"<br/>"); document.write(parseFloat("a120px")+"<br/>"); </script> </head> <body> </body> </html>