String(value)

  1. 返回值类型是 string value
  2. 根据传入的值是否为空字符串,选择性调用 ToString(value) 方法

代码

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 无限大和无限小的数值,包括能表示能存储下的正常浮点数

以下 m 代替传入的 Number 类型的参数的值

  • 当 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’.

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.

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.

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).

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).

通俗的理解就是 科学计数法表示

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


_ipo
179 声望15 粉丝

bug