【发布时间】:2021-01-03 19:19:10
【问题描述】:
这是代码:
var input = prompt("Enter a decimal value");
console.log(input +" the binary value would be:", Number.parseInt(input, 2));
1 和 2 的输出是正确的,但从 3 开始显示 NaN。
它适用于以下代码:
var input = Number(prompt("Enter a decimal value"));
console.log(input +" the binary value would be:", input.toString(input, 2));
我想知道为什么它不适用于第一个代码。
【问题讨论】:
-
您的第二个代码为 3 产生 10。
-
与 @Alex 的字符串无关,因为这就是 parseInt 所期望的
-
问题是二进制的基数是 2,但 OP 没有传递二进制字符串来获得十进制等效值。
-
我在你的第二次测试中放了一个更高的数字,
Uncaught RangeError: toString() radix argument must be between 2 and 36.. 事情变得有趣了 -
@TheBombSquad 这是因为他们将输入作为基数传递。这两个代码示例实际上都没有按照用户的期望进行。
标签: javascript console.log parseint