javascript - Number.parseInt() 不断返回 NaN
问题描述
我正在研究 JavaScript 中的二进制到十进制和十进制到二进制转换器,并认为我会尝试使用 Number.parseInt() 来解决这个问题。也就是说,我的输出一直显示“NaN”而不是所需的转换。对此的任何帮助将不胜感激!
// Get binary number from user for decimal conversion
let binary = document.getElementById("binary").value;
// Set the base (radix) to 2 for decimal conversion
let binBase = 2;
// Get decimal number from user for binary conversion
let decimal = document.getElementById("decimal").value;
// Set the base (radix) to 10 for binary conversion
let decBase = 10;
// Function to convert binary to decimal
function getDecimal(binary, binBase) {
let finalDec = Number.parseInt(binary, binBase);
// Output the decimal number
document.getElementById("showDecimal").innerHTML = finalDec;
return finalDec;
}
// Function to convert decimal to binary
function getBinary(decimal, decBase) {
let finalBin = Number.parseInt(decimal, decBase);
// Output the binary number
document.getElementById("showBinary").innerHTML = finalBin;
return finalBin;
}
<html>
<head>
<meta charset="UTF-8">
<title>Binary to Decimal and Back Converter</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Please Enter the Binary Number (Base 2) That You Would Like Converted to Decimal Form (Base 10)</h3>
Binary: <input type="text" id="binary" value="">
<button onclick="getDecimal()">Calculate</button>
The Decimal Number Is:
<p id="showDecimal"></p>
<h3>Please Enter the Decimal Number (Base 10) that You Would Like Converted to Binary Form (Base 2)</h3>
Decimal: <input type="text" id="decimal" value="">
<button onclick="getBinary()">Calculate</button>
The Binary Number Is:
<p id="showBinary"></p>
<script src="script.js"></script>
</body>
</html>
它在浏览器中的外观图片:
在此先感谢您的帮助!
解决方案
单击按钮时获取输入字段值:
// Function to convert binary to decimal
function getDecimal() {
var binary = document.getElementById("binary").value;
let finalDec = Number.parseInt(binary, 2);
// Output the decimal number
document.getElementById("showDecimal").innerHTML = finalDec;
return finalDec;
}
// Function to convert decimal to binary
function getBinary() {
var decimal = document.getElementById("decimal").value;
let finalBin = Number.parseInt(decimal, 10).toString(2);
// Output the binary number
document.getElementById("showBinary").innerHTML = finalBin;
return finalBin;
}
二进制数也必须格式化为.toString(2)
推荐阅读
- javascript - JavaScript 函数
- php - 正则表达式排除被特殊字符包围的单词
- json - 消息有效负载的 JSON 结构
- php - 如何从 php 中的 html 中的锚标记中获取值
- javascript - 如何将 HTML 代码转换为 JSON 对象?
- google-cloud-firestore - Firestore 安全规则和自定义声明 - 可以使用覆盖它们吗?
- c++ - 回溯功能 - 仅显示以字母 a 开头和结尾的单词
- python - 子类化小部件以覆盖方法,同时保留原始方法功能
- django - 当我单击 bms_homepage.html 中的登录按钮时,为什么“找不到页面”?
- laravel - Laravel 500 | UBUNTU 16.04 上的服务器错误