猿问

10%0 结果为NaN?

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

10 % 0;

> NaN

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


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


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


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


所以我觉得最终返回的 NaN 还是有某个地方的运算是有问题的。

比如我们都知道 'a'/10 ,结果是NaN,因为一个字符,一个是数字,报错是理所当然的。但是 10%0 为何报错为NaN?


胡说叔叔
浏览 671回答 1
1回答

达令说

这种问题你想知道结果,只能去看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 resultequals 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.看我加粗的那句话,这就不需要我翻译了吧。。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答