# toString
# Description
转换 value 为字符串。 null 和 undefined 将返回空字符串。-0 将被转换为字符串 "-0"。
# Params
value
# Return
String
# Depend
import isSymbol from './isSymbol.js'
# 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
如果传入的
value == null,则返回 空字符串,这里使用==,兼容了undefined如果传入的
value本身typeof就是字符串,则直接返回value针对数组的处理,这里使用了递归调用进行处理,与
Array.prototype.toString不同的是,lodash的toString可以处理数组中的Symbol以及将-0转为'-0', 原生的Array.prototype.toString在处理Symbol时 会报Uncaught TypeError: Cannot convert a Symbol value to a string如果
value为symbol类型,则直接调用Symbol.prototype.toString方法进行处理使用模板字符串转换为字符串型,到最后做了
-0的判断,正确的返回了字符串'-0'
# Remark
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)
# 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