zl程序教程

您现在的位置是:首页 >  其它

当前栏目

_.toString(value)

value _. toString
2023-09-11 14:15:01 时间

172

_.toString(value)
_.toString将一个值转换成字符串,null或者undefined被转换成空字符串。-0的符号被保留

参数

value (*): 需要转换的值

返回值

(string): 返回转换好的字符串

例子

_.toString(null);
// => ''
 
_.toString(-0);
// => '-0'
 
_.toString([1, 2, 3]);
// => '1,2,3'

源代码

import map from './map.js'
import isSymbol from './isSymbol.js'

/** Used as references for various `Number` constants. */
const INFINITY = 1 / 0

/** Used to convert symbols to primitives and strings. */
const symbolProto = Symbol ? Symbol.prototype : undefined
const symbolToString = symbolProto ? symbolProto.toString : undefined

/**
 * Converts `value` to a string. An empty string is returned for `null`
 * and `undefined` values. The sign of `-0` is preserved.
 *
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {string} Returns the converted string.
 * @example
 *
 * toString(null)
 * // => ''
 *
 * toString(-0)
 * // => '-0'
 *
 * toString([1, 2, 3])
 * // => '1,2,3'
 */
//将一个值转换成字符串,null或者undefined被转换成空字符串。-0的符号被保留
function toString(value) {
  if (value == null) {//如果value等于null或者undefined返回空字符串
    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).
    //递归地转换value数组变成字符串
    return `${map(value, (other) => other == null ? other : toString(other))}`
  }
  if (isSymbol(value)) {//如果是Symbol对象
    return symbolToString ? symbolToString.call(value) : ''//调用Symbol.prototype.toString处理
  }
  const result = `${value}`//使用模板字符串转换成字符串格式
  return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result//处理负数0的情况
}

export default toString