10%0 结果为NaN?

任何数取余0,为什么结果为NaN;

10 % 0;
> NaN

感谢各位的解答,我觉得还是有些欠妥当。

都知道 任何数 /0 得到的是 Infinity 无穷大的,虽然 %0的计算过程中也涉及除法运算,但是它的结果却是NaN 而不是 Infinity

本质上是有区别的,javascript指南中提到: 算术运算中使用了不恰当的的操作数,导致【运算失败】,该运算就会返回 NaN

然而 任何数 /0 返回的是 Infinity,这代表的是运算是 【成功】 的。

所以我觉得最终返回的 NaN 还是有某个地方的运算是有问题的。
比如我们都知道 'a'/10 ,结果是NaN,因为一个字符,一个是数字,报错是理所当然的。但是 10%0 为何报错为NaN?

阅读 5.8k
6 个回答

这种问题你想知道结果,只能去看ECMAScript 标准,因为一个取模(余数)运算的定义里,小学生都知道被除数需要是非0,对于这种情况如何处理?当然是标准说怎么处理,就怎么处理
es7标准

找到关于 % opeartor的定义

12.7.3.3 Applying the % Operator:

  • If either operand is NaN, the result is NaN.
  • The sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result
    equals the dividend.

If the dividend is a zero and the divisor is nonzero and finite, the result is the same as the dividend. In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from a dividend n and a divisor d is defined by the mathematical relation r = n - (d × q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d. r is computed and rounded to the nearest representable value using IEEE 754-2008 round to nearest, ties to even mode.

看我加粗的那句话,这就不需要我翻译了吧。。

你用数学算10/0 余是多少,你能得出来结果么。

0 是不可以作为分子的, 同理, 对 0 取余, 本身就报错了

NaN的意思是not a number,你应该在做除法取余运算之前先判断除数是否为0

mozilla英文社区对%的解释

%调用了javascript语言内置的函数来计算结果。
该内置函数的计算结果即:整型余数。
该整形余数的符号,与被除数保持一致。这是求余运算的特征
而取模运算的特征为:计算结果符号与除数保持一致。


内置机制就是这样的 是个定理 就和1+1 =2一样的
你只要知道结果,怎么来的是验证不了的
或则你可以去问设计js 的人,开始为什么要定义成这个结果
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题