# toString

# Description

转换 value 为字符串。 nullundefined 将返回空字符串。-0 将被转换为字符串 "-0"

# Params

value

# Return

String

# Depend

import isSymbol from './isSymbol.js'

isSymbol 源码分析

# Code

const INFINITY = 1 / 0

function toString(value) {
  if (value == null) {
    return ''
  }
  // Exit early for strings to avoid a performance hit in some environments.
  if (typeof value === 'string') {
    return value
  }
  if (Array.isArray(value)) {
    // Recursively convert values (susceptible to call stack limits).
    return `${value.map((other) => other == null ? other : toString(other))}`
  }
  if (isSymbol(value)) {
    return value.toString()
  }
  const result = `${value}`
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result
}

# Analyze

  1. 如果传入的 value == null ,则返回 空字符串,这里使用 == ,兼容了 undefined

  2. 如果传入的 value 本身 typeof 就是字符串,则直接返回 value

  3. 针对数组的处理,这里使用了递归调用进行处理,与 Array.prototype.toString 不同的是,lodashtoString 可以处理数组中的 Symbol 以及将 -0 转为 '-0' , 原生的 Array.prototype.toString 在处理 Symbol 时 会报 Uncaught TypeError: Cannot convert a Symbol value to a string

  4. 如果 valuesymbol 类型,则直接调用 Symbol.prototype.toString 方法进行处理

  5. 使用模板字符串转换为字符串型,到最后做了 -0 的判断,正确的返回了字符串 '-0'

# Remark

  1. Number.prototype.toString ECMAScript 2015 (opens new window)

2.Number.prototype.toString() MDN (opens new window)Object.prototype.toString() MDN (opens new window)RegExp.prototype.toString() MDN (opens new window)BigInt.prototype.toString() MDN (opens new window)Function.prototype.toString() MDN (opens new window)Boolean.prototype.toString() MDN (opens new window)Error.prototype.toString() MDN (opens new window)Symbol.prototype.toString() MDN (opens new window)Date.prototype.toString() MDN (opens new window)Array.prototype.toString() MDN (opens new window)String.prototype.toString() MDN (opens new window)

  1. Strict equality (===) MDN (opens new window) -- ECMA (opens new window)

  2. 相等(==) MDN (opens new window)

  3. 模板字面量(模板字符串) MDN (opens new window)

  4. Number.NEGATIVE_INFINITY MDN (opens new window)

  5. Number.POSITIVE_INFINITY MDN (opens new window)

# Example

toString([null,2,undefined,Symbol(1),[1,[2,[3]]]]) // ,2,,Symbol(1),1,2,3
toString('3') // 3
toString(3) // 3
toString(-0) // -0