es String 內部實現邏輯標準

String(value)

  1. 返回值類型是 string value
  2. 根據傳入的值是否爲空字符串,選擇性調用 ToString(value) 方法

代碼git

function String(value) {
    return value === "" ? "" : ToString(value)
}

ToString(value)

ToString 是一個抽象的操做,將傳入的參數值轉換爲 String 類型的值,這一過程是參照一個規則進行,規則以下表
傳入參數的類型 返回的結果
Undefined "undefined"
Null "null"
Boolean true => "true" false => "false"
String 返回 參數值
Number 參考下面詳細闡述
Object 1. 調用 ToPrimitive 方法,var primValue = ToPrimitive(input argument hintString); 2. 返回 ToString(primValue)

詳細闡述 Number 類型

Number 包括 NaN 特殊的數值,還包括 Infinity 無限大和無限小的數值,包括能表示能存儲下的正常浮點數github

如下 m 代替傳入的 Number 類型的參數的值segmentfault

  • 當 m 爲 NaN,返回 String 形的 "NaN"
  • 當 m 爲 +0 或者 -0,返回 String 形的 "0"
  • 當 m < 0, 返回 -ToString(-m),意思是首先提取出 - 符號,再對 -m 調用 ToString 方法
  • 當 m 爲 infinity,返回 String 形的 "Infinity"
  • 如下爲重點,當 m > 0 且不是 infinity 時的內部抽象操做
Otherwise, let n, k, and s be integers such that k ≥ 1, 10k−1 ≤ s < 10k, the Number value for s × 10n−k is m, and k is as small as possible. Note that k is the number of digits in the decimal representation of s, that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely determined by these criteria.

If k ≤ n ≤ 21, return the String consisting of the k digits of the
decimal representation of s (in order, with no leading zeroes),
followed by n−k occurrences of the character ‘0’.es5

If 0 < n ≤ 21, return the String consisting of the most significant n
digits of the decimal representation of s, followed by a decimal point
‘.’, followed by the remaining k−n digits of the decimal
representation of s.code

If −6 < n ≤ 0, return the String consisting of the character ‘0’,
followed by a decimal point ‘.’, followed by −n occurrences of the
character ‘0’, followed by the k digits of the decimal representation
of s.ci

Otherwise, if k = 1, return the String consisting of the single digit
of s, followed by lowercase character ‘e’, followed by a plus sign ‘+’
or minus sign ‘−’ according to whether n−1 is positive or negative,
followed by the decimal representation of the integer abs(n−1) (with
no leading zeros).rem

Return the String consisting of the most significant digit of the
decimal representation of s, followed by a decimal point ‘.’, followed
by the remaining k−1 digits of the decimal representation of s,
followed by the lowercase character ‘e’, followed by a plus sign ‘+’
or minus sign ‘−’ according to whether n−1 is positive or negative,
followed by the decimal representation of the integer abs(n−1) (with
no leading zeros).字符串

通俗的理解就是 科學計數法表示get

參考
http://es5.github.io/#x15.5.1.1
http://es5.github.io/#x9.8input

相關文章
相關標籤/搜索