转换为数字

/**
 * Converts `value` to a number.
 *
 * @param {*} value The value to process
 * @returns {number} Returns the number.
 * @example
 *
 * toNumber('3')
 *  // => 3
 *
 * toNumber(Number.MIN_VALUE)
 *  // => 5e-324
 *
 * toNumber(Infinity)
 * // => Infinity
 *
 * toNumber('0b111110111')
 * // => 503
 *
 * toNumber('0o767')
 *  // => 503
 *
 * toNumber(new Date())
 * // => 1561389053138
 *
 * toNumber(() => {})
 *  // => NaN
 */

const NAN = 0 / 0
const symbolTag = "[object Symbol]"
const reTrim = /^\s+|\s+$/g
const reIsBinary = /^0b[01]+$/i
const reIsOctal = /^0o[0-7]+$/i
const reIsBadHex = /^[-+]0x[0-9a-f]+$/i

function isObjectLike(value) {
  return typeof value == "object" && value !== null
}

function isSymbol(value) {
  return (
    typeof value === "symbol" ||
    (isObjectLike(value) && Object.prototype.toString.call(value) === symbolTag)
  )
}

function isObject(value) {
  var type = typeof value
  return value != null && (type === "object" || type === "function")
}

function toNumber(value) {
  if (typeof value === "number") {
    return value
  }
  if (isSymbol(value)) {
    return NAN
  }
  // valueOf返回指定对象的原始值, new Data()例外 它返回时间戳
  if (isObject(value)) {
    var other = typeof value.valueOf === "function" ? value.valueOf() : value //判断对象中是否有valueOf这个方法
    value = isObject(other) ? other + "" : other
  }
  if (typeof value != "string") {
    return value === 0 ? value : +value
  }
  //处理是字符串的情况
  value = value.replace(reTrim, "") //去掉前后的空格
  const isBinary = reIsBinary.test(value) //判断是否是二进制、八进制、十六进制
  return isBinary || reIsOctal.test(value)
    ? parseInt(value.slice(2), isBinary ? 2 : 8)
    : reIsBadHex.test(value)
    ? NAN
    : +value
}

export default toNumber
//方法二

const symbolTag = "[object Symbol]"
const NAN = 0 / 0

function isObjectLike(value) {
  return typeof value == "object" && value !== null
}

function isSymbol(value) {
  return (
    typeof value === "symbol" ||
    (isObjectLike(value) && Object.prototype.toString.call(value) === symbolTag)
  )
}

function toNumber(value) {
  if (typeof value === "number") {
    return value
  }

  if (isSymbol(value)) {
    return NAN
  }

  return Number(value)
}

export default toNumber

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值