_.toNumber(value)

169

_.toNumber(value)

_.toNumber将一个值转换成数字

参数

value (*): 需要转换的值

返回值

(number): 返回转换好的数值

例子

_.toNumber(3.2);
// => 3.2
 
_.toNumber(Number.MIN_VALUE);
// => 5e-324
 
_.toNumber(Infinity);
// => Infinity
 
_.toNumber('3.2');
// => 3.2

源代码

import isObject from './isObject.js'
import isSymbol from './isSymbol.js'

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

/** Used to match leading and trailing whitespace. */
const reTrim = /^\s+|\s+$/g

/** Used to detect bad signed hexadecimal string values. */
const reIsBadHex = /^[-+]0x[0-9a-f]+$/i

/** Used to detect binary string values. */
const reIsBinary = /^0b[01]+$/i

/** Used to detect octal string values. */
const reIsOctal = /^0o[0-7]+$/i

/** Built-in method references without a dependency on `root`. */
const freeParseInt = parseInt

/**
 * Converts `value` to a number.
 *
 * @since 4.0.0
 * @category Lang
 * @param {*} value The value to process.
 * @returns {number} Returns the number.
 * @see isInteger, toInteger, isNumber
 * @example
 *
 * toNumber(3.2)
 * // => 3.2
 *
 * toNumber(Number.MIN_VALUE)
 * // => 5e-324
 *
 * toNumber(Infinity)
 * // => Infinity
 *
 * toNumber('3.2')
 * // => 3.2
 */
//将一个值转换成数字
function toNumber(value) {
  if (typeof value == 'number') {//如果是number直接返回
    return value
  }
  if (isSymbol(value)) {//如果是Symbol类型,返回NaN
    return NAN
  }
  if (isObject(value)) {//如果value是对象
    const other = typeof value.valueOf == 'function' ? value.valueOf() : value
    //如果value有valueOf属性,就调用valueOf()取值,否则取原值
    value = isObject(other) ? `${other}` : other
    //如果other是对象,就转成字符串,否则取原值
  }
  if (typeof value != 'string') {//value被转成字符串后的处理
    return value === 0 ? value : +value
  }
  value = value.replace(reTrim, '')//正则把空白字符都转换成空字符串
  const isBinary = reIsBinary.test(value)//判断是否是二进制
  return (isBinary || reIsOctal.test(value))
    ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
    : (reIsBadHex.test(value) ? NAN : +value)
    //如果是二进制或者八进制,调用parseInt转换
    //否则判断不良签名的十六进制转为NaN
}

export default toNumber

 

posted @ 2019-01-15 16:18  hahazexia  阅读(1248)  评论(0)    收藏  举报