parseFloat 会抛出错误吗?

Does parseFloat ever throw an error?

在我正在处理的代码库中,我遇到了这样的代码:

try {
    price = parseFloat(price);
} catch (err) {
    console.log(err);
}

我知道在大多数情况下 price 无法转换为数字,它只会获取 NaN 的值。我的问题是:是否存在它会抛出错误的情况,使得 try-catch-construction 成为必要?

parseFloat() 本身仅 returns 并且从不抛出错误。但是,如果变量 price 尚未在上下文中声明,您将收到如下错误:

Uncaught ReferenceError: price is not defined

它解释了它周围有一个 try/catch 块的原因。

所以回答你的问题:是的,如果你不能相信以前的 js execution/context(例如由于广告拦截器或类似的原因),那么在某些情况下是必要的,但不,它不是函数 parseFloat() 抛出错误的是解释器。

简答:否

来自 MDN

A floating point number parsed from the given string. If the first character cannot be converted to a number, NaN is returned

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat

are there cases where it will throw an error, making the try-catch-construction necessary?

是的。除了引用错误(因为 price 未声明)或 parseFloat 被非函数之类的东西覆盖之外,内置 parseFloat 也可以抛出异常.

但是,当您传入字符串时,它不会抛出错误。它只会在尝试将参数转换为字符串失败并出现异常时抛出。这方面的例子包括:

  • 传递符号
  • 不使用 [Symbol.toPrimitive].valueOf.toString 方法传递对象
  • 传递其中一种方法抛出的对象
  • 传递一个对象,其中 none 这些方法 return 原始