本篇文章帶給大家的內容是關於javascript中的數值如何進行強制轉換? (方法總結),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
javascript資料型別分為基本資料型別和引用資料型別
基本資料:Number, Boolean, Undefined, Null, String;
引用資料:Object;
當0.000...01,小數點後大於等於7位元時會自動轉換成科學計數法
當20000...00,當整數部分大於等於22位元時會自動轉換成科學計數法。
Number(x):一個參數;
參數為Number型別時:能正確輸出;
console.log(Number(1)); //1 console.log(Number(1e-7)); //1e-7 console.log(Number(0b111)); //7 console.log(Number(NaN)); //NaN
參數為Boolean類型時:true->1;fasle->0;
console.log(Number(true)); //1 console.log(Number(false)); //0
參數為undefined時:其值為NaN
console.log(Number(undefined)); //NaN
參數為null時:
console.log(Number(null)); //0
參數為String類型時:
//数字字符串 console.log(Number("123")); //123 console.log(Number("-123")); //-123 console.log(Number("12.3")); //12.3 console.log(Number("1e-7")); //1e-7 console.log(Number("0xff")); //255 console.log(Number("00123")); //123 console.log(Number(" 123")); //123 console.log(Number("\t\n123")); //123
//数字+字符或全字符字符串 console.log(Number('a123')); //NaN console.log(Number("false")); //NaN console.log(Number("a123")); //NaN
//空串或者空格字符串 console.log(Number("\t\n")); //0 console.log(Number(" ")); //0 console.log(Number("")); //0
參數型別是物件時:先進行.valueOf(),如得到的時物件再進行toString(),待得到基本資料型別為止,例如{}.valueOf().toString() = "[object Object]" 最後number的結果就是NaN了
console.log(Number({})); //NaN console.log(Number([1])); //1 console.log(Number([1,2])); //NaN cosole.log(Number([])); //0
流程是:先String(x)變成字串,再將該值以y進位為基底轉為十進位數,不填著為10,y的範圍: [2,36]
x參數為number時:值得注意??的是0.001,1e-7型別的值,會捨去小數點(e)後面的數值,傳回前面的。
console.log(parseInt(123)); //123 console.log(parseInt(1e-7)); //1 console.log(parseInt(0xff)); //255 console.log(parseInt(NaN)); //NaN console.log(parseInt(0.00001)); //0
x參數為boolean,undefined,null時:
console.log(parseInt(true)); //NaN console.log(parseInt(false)); //NaN console.log(parseInt(undefined)); //NaN console.log(parseInt(null)); //NaN
x參數為String類型時:需要注意的時空字串,空格字串,數字字元
console.log(parseInt("")); //NaN console.log(parseInt("-123")); //-123 console.log(parseInt(" ")); //NaN console.log(parseInt("\t\n")); //NaN console.log(parseInt("a123")); //NaN console.log(parseInt("123a")); //123
參數x為物件時:同理透過.valueOf(),如得到的時物件再進行toString(),待得到基本資料型別為止,然後按上述規則進行輸出
console.log(parseInt({1:2})); //"[object Object]"->NaN console.log(parseInt([])); //""->NaN console.log(parseInt([1,2])); //"1,2"->//1
console.log(parseInt("f",2)); //NaN console.log(parseInt("11f",2); //3 console.log(parseInt("123",37)); //NaN console.log(parseInt("0xff",0)); //255 console.log(parseInt("0xff",NaN)); //255 console.log(parseInt("ff",[])); //NaN
console.log(parseFloat(0xff)); //255 console.log(parseFloat("0xff")); //0 console.log(parseInt("0xff")); //255 个人猜测parseInt(x,y)有y的存在所以能正确输出 console.log(parseFloat(1e22)); //1e22 console.log(parseFloat(1e-7)); //1e-7 console.log(parseFloat("00123")); //123 console.log(parseFloat(" ")); //NaN
console.log(String(null)); //"null" console.log(0xff.toString(2)); //"11111111" console.log(oxff.toString()); //"255" 不填默认10进制
以上是javascript中的數值如何進行強制轉換? (方法總結)的詳細內容。更多資訊請關注PHP中文網其他相關文章!