Data type conversion of JavaScript variables
The type conversion of variables is usually automatically converted by JS, but sometimes manual conversion is required.
##Convert other types to Boolean
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var x1 = "abc"; //true var x2 = "110"; //true var x3 = ""; //false var x4 = 110; //true var x5 = 0; //false var x6 = NaN; //false var x7 = undefined; //false var x8 = null; //false //驗(yàn)證我們的注釋結(jié)果是否正確 //使用Boolean()全局函數(shù),強(qiáng)制將變量轉(zhuǎn)化成布爾型 var result = Boolean(x1); //輸出變量的類型和結(jié)果 document.write(x1+"轉(zhuǎn)布爾型的轉(zhuǎn)換結(jié)果為:"+result); </script> </head> <body> </body> </html>
Note: We only forced one conversion, you can also use the forced conversion function to convert the rest and view the output results
Convert other types into character types
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var x1 = true; //true var x2 = false; //false var x4 = 110; //110 var x5 = 0; //0 var x6 = NaN; //NaN var x7 = undefined; //undefined var x8 = null; //null //驗(yàn)證我們的注釋結(jié)果是否正確 //使用String()全局函數(shù),強(qiáng)制將變量轉(zhuǎn)化成字符型 var result = String(x1); //輸出變量的類型和結(jié)果 document.write(x1+"轉(zhuǎn)字符型的轉(zhuǎn)換結(jié)果為:"+result); </script> </head> <body> </body> </html>Note: Please test the others carefully. If you encounter unclear conversion in the future, please remember to use the forced conversion function
Convert other types to numeric types
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>php.cn</title> <script> var x1 = true; //1 var x2 = false; //0 var x3 = "120px"; //NaN var x4 = 100; //100 var x5 = ""; //0 var x6 = undefined; //NaN var x8 = null; //0 //驗(yàn)證我們的注釋結(jié)果是否正確 //使用Number()全局函數(shù),強(qiáng)制將變量轉(zhuǎn)化成數(shù)值型 var result = Number(x1); //輸出變量的類型和結(jié)果 document.write(x1+"轉(zhuǎn)數(shù)值型的轉(zhuǎn)換結(jié)果為:"+result); </script> </head> <body> </body> </html>