为什么parseInt(1 / 0,19)返回18? [英] Why does parseInt(1/0, 19) return 18?

查看:388
本文介绍了为什么parseInt(1 / 0,19)返回18?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中遇到了一个恼人的问题。

I've an annoying problem in JavaScript.

> parseInt(1 / 0, 19)
> 18

为什么 parseInt 返回 18

推荐答案

1/0的结果 Infinity

parseInt 将其第一个参数视为字符串,这意味着首先 Infinity.toString()被调用,产生字符串Infinity。所以它的工作方式与你要求它将基数19中的Infinity转换为十进制相同。

parseInt treats its first argument as a string which means first of all Infinity.toString() is called, producing the string "Infinity". So it works the same as if you asked it to convert "Infinity" in base 19 to decimal.

这里是基数19中的数字及其十进制值:

Here are the digits in base 19 along with their decimal values:

Base 19   Base 10 (decimal)
---------------------------
   0            0
   1            1
   2            2
   3            3
   4            4
   5            5
   6            6
   7            7
   8            8
   9            9
   a            10
   b            11
   c            12
   d            13
   e            14
   f            15
   g            16
   h            17
   i            18

接下来会发生什么 parseInt 扫描输入Infinity找到它的哪部分可以解析并在接受第一个 I 后停止(因为 n 不是一个val基数19)中的id数字。

What happens next is that parseInt scans the input "Infinity" to find which part of it can be parsed and stops after accepting the first I (because n is not a valid digit in base 19).

因此它的行为就像你调用 parseInt(I,19) ,在上表中转换为十进制数。

Therefore it behaves as if you called parseInt("I", 19), which converts to decimal 18 by the table above.

这篇关于为什么parseInt(1 / 0,19)返回18?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆