JS中parseInt()、Numer()深度解析


JS中字符串轉換為數字有兩種方式:

1、parseInt函數

定義:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/parseInt

語法:parseInt(string [ , radix])

參數:

    string:要被解析的值。如果參數不是一個字符串,則將其轉換為字符串。字符串開頭的空白符將會被忽略。

    radix:一個2到36之間的整數值,用於指定轉換中采用的基數。

        如果省略該參數或者為0,則數字將以 10 為基礎來解析。

        如果string以 “0x” 或 “0X” 開頭,將以 16 為基數。

        如果string以“0” 開頭,在ECMA3中被認為是8進制;但是在ECMA5中已經強制規定此情況默認是10進制

        如果該參數小於 2 或者大於 36,則 parseInt() 將返回 NaN。

 

在ECMA規范中,對於parseInt函數解析字符串為數字的步驟如下:

 

看看V8中parseInt函數的源碼:【只列出一部分,如需要查看請參見V8中src/conversions-inl.h和src/compiler/js-builtin-reducer.cc】

if (radix == 0) { //如果傳入radix是0,則以10進行處理
    // Radix detection.
    radix = 10;
    if (*current == '0') {
      ++current;
      if (current == end) return SignedZero(negative);
      if (*current == 'x' || *current == 'X') {
        radix = 16;
        ++current;
        if (current == end) return JunkStringValue();
      } else {
        leading_zero = true;
      }
    }
  } else if (radix == 16) { //16進制
    if (*current == '0') {
      // Allow "0x" prefix.
      ++current;
      if (current == end) return SignedZero(negative);
      if (*current == 'x' || *current == 'X') {
        ++current;
        if (current == end) return JunkStringValue();
      } else {
        leading_zero = true;
      }
    }
  }
 
  if (radix < 2 || radix > 36) return JunkStringValue(); //radix不在2~36之間的處理

  

例如解析:

    parseInt('0101' , 1)   => NaN

    parseInt('453' , 2) => NaN  因為453不符合二進制數字,所以無法轉換出正確的數字

 

2、Number()函數

定義:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number

計算步驟:

 

兩種方法的區別:

參考鏈接:http://www.w3school.com.cn/js/pro_js_typeconversion.asp

用 Number() 進行強制類型轉換,並且是轉換整個字符串值,如果整個字符串不能轉換成數字,則輸出NaN。

 

例如:

parseInt('01a02', 10)  => 1    parseInt('1.22.22', 10) => 1         parseInt('1.22' , 10) => 1

Number('01a02') => NaN      Number('1.22.22') => NaN          Number('1.22')  =>  1.22

 

JS中數字利用parseInt進行轉換成整數:

由parseInt中定義:parseInt是用於將字符串根據基數轉換成整數,如果傳入參數不是字符串,會首先利用toString方法轉換為字符串,再轉換為整數

例子:

parseInt(0.000001)   =>  0    parseInt('0.000001')    =>  0

parseInt(0.0000001) => 1     parseInt('0.0000001')  =>  0

轉換0.000001和0.0000001數字時出現結果不同,那么先將看看這兩個數字轉換為字符串的結果:

var a = 0.000001   ;   a.toString() ;  => '0.000001'

var b = 0.0000001 ;   b.toString() ;  => '1e-7'

由此不難看出:為什么會出現上述結果。

 

究其原因:在ECMA規范中

 

可以解釋0.000001和0.0000001轉換為字符串后的不同結果。

所以在日常使用parseInt函數時:常用的情況無非為將字符串轉換為整數或者將數字轉換為整數,所以在使用將數字轉換為整數時,最好需要進行判斷

 

function newParseInt(value) {

     if(typeof value === 'number') {

         return Math.floor(value);

    }

    return parseInt(value);

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM