一个看似奇怪的问题,正常我们预期这个结果应该是0才对,结果却是7,令人意外。参考ECMAScript标准里面的描述

The parseInt function produces an integral Number dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the code unit pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the code unit pairs 0x or 0X.

parseInt这个函数接受的是string类型的参数,所以在这里第一步会把这个小数0.0000007转换为字符串。

The parseInt function is the %parseInt% intrinsic object. When the parseInt function is called, the following steps are taken:

  1. 1. 1. Let inputString be ? ToString(string).
  2. 2. 2. Let S be ! TrimString(inputString, start).

在通常的情况下,小数转换为字符串是这样的:

String(0.7);      // => '0.7'
String(0.07);     // => '0.07'
String(0.007);    // => '0.007'
String(0.0007);   // => '0.0007' 
String(0.00007);  // => '0.00007'
String(0.000007); // => '0.000007'

现在问题来了,0.0000007转换为字符串不是上面这样的,而是下面这样的:

String(0.0000007); // => '7e-7'

所以接下来这个表达式转换为parseInt(‘7e-7’),在此种情况下,ECMAScript的描述是这样的:

parseInt may interpret only a leading portion of string as an integer value; it ignores any code units that cannot be interpreted as part of the notation of an integer, and no indication is given that any such code units were ignored.

转换为整数时只取字符串前面的数字部分,非数字开始的字符及后面的都会被忽略。所以在这个情况下会返回7,其他的部分会忽略。

因此建议大家,请确保参数是字符串之后再使用parseInt,否则请使用Math.roundMath.floor或者Math.ceil方法。

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.