javascript - a.b < 0,为什么当 a.b === undefined 时不会抛出错误?

标签 javascript node.js comparison throw operands

拼写错误最终为

a.b > 0

a.b 未定义。根据 MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators#Greater_than_operator),比较对操作数调用 .valueOf()。所以应该是这样

a.b.valueOf() > 0

但这实际上引发了一个似乎没有发生的错误。相反,这似乎被评估:

undefined > 0

我是不是误会了什么?

就我而言,这导致 Node.js 代码中出现无提示错误。我当然希望抛出一个错误。

我可以在不显式检查操作数的情况下处理这个问题吗?

<小时/>

编辑:freeCodeCamp 似乎对此的描述比 MDN 更正确:

https://guide.freecodecamp.org/javascript/comparison-operators/

但我仍然想知道处理这个问题的最简单方法,而不会被简单的拼写错误所困扰。

最佳答案

请参阅specification :它的作用is :

  1. Let r be the result of performing Abstract Relational Comparison lval < rval.

其中does ,它首先尝试将每一方强制为原始:

a. Let px be ? ToPrimitive(x, hint Number).

b. Let py be ? ToPrimitive(y, hint Number).

undefined已经是一个原始的 - 没有抛出任何异常。然后,它会:

Let nx be ? ToNumeric(px).

Let ny be ? ToNumeric(py).

选 Angular undefined to a Number 也不会抛出异常,但会返回 NaN :

console.log(Number(undefined));

那么我们就开始

If Type(nx) is the same as Type(ny), return Type(nx)::lessThan(nx, ny).

哪里nxNaNny是 0。lessThan返回undefinednxNaN ,描述here :

  1. If x is NaN, return undefined.

然后,回到 5. 之后的步骤在答案的开头:

  1. If r is undefined, return false. Otherwise, return r.

结果是undefined ,所以false返回(没有抛出错误)。

<小时/>

So it should be

  a.b.valueOf() > 0

只有对象才会有valueOf过程中调用了它<评估(在上面的 a. Let px be ? ToPrimitive(x, hint Number). 中)。 undefined不是一个对象 - 它已经是一个基元,因此该步骤不会发生额外的转换。

I certainly wanted that an error was thrown instead.

Can I handle this without explicitly checking the operands?

不是真的,但这应该不难做到 - 只需检查 a.b如果您不确定的话,首先是一个数字。 if (typeof a.b === 'number') 。这没有什么问题。

关于javascript - a.b < 0,为什么当 a.b === undefined 时不会抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617590/

相关文章:

javascript - 如何使用 JQuery 检索无序列表的 li 标签并将这些标签放入数组中?

javascript - 为什么 useMemo 不起作用?我用错了吗?

PHP 与 JavaScript 切换缩进

node.js - 如何使用批处理文件运行一个简单的 node.js 文件

sql - 作为字符串的整数比较

javascript - Passport/done 函数和 passReqToCallBack 可以一起使用吗?

node.js - Express错误处理中的代码质量检查与隐式next()之间的冲突

javascript - 无法加载资源 - Socket.IO

检查颜色相似性的算法

mysql - Oracle RDBMS 是否比 MySQL RDBMS 更稳定、更安全、更健壮等?