我无法弄清楚我做错了什么导致我的for循环不能通过我的长度。我试图使用用户输入将二进制转换为十进制,但它无法正常工作。我拥有的是什么
编辑
var val = $("txtIn").value;
if (cT[1].checked) {
var bVal = val;
if (isNaN(bVal)) {
alert(val + " is not a number. A number is required to run the program.");
} else if ((val % 1) !== 0) {
alert(val + " is not an integer. A whole number is required to run the program.");
} else if (bVal < 0) {
alert(val + " is not able to convert. Input must be positive integer.");
} else {
convertByArrayB(bVal);
}
}
function convertByArrayB(bVal) {
var r, i, j;
for (i = 0; i < bVal.length; i++) {
r = bVal.charAt(i);
if (r !== '1' && r !== '0') {
alert("You did not enter a valid binary number. Please try again!");
}
var nv = parseInt(r, 2);
}
$("txtOut").value = nv;
}
我不认为你需要顶部,但比抱歉更安全。预先感谢您的任何帮助。 (喜欢这个社区BTW)
当你这样做时,你正在改变循环中的bVal
:
bVal = nv;
所以bVal.length
的值在下一次迭代时是undefined
,循环停止。
调用parseInt()
的代码应该在循环之后,而不是在循环之内。没有必要重新分配bVal
,它应该解析bVal
,而不是r[i]
。
function convertByArrayB(bVal) {
var r, i, j;
for (i = 0; i < bVal.length; i++) {
r = bVal.charAt(i);
if (r !== '1' && r !== '0') {
alert("You did not enter a valid binary number. Please try again!");
return;
}
}
var nv = parseInt(bVal, 2);
document.getElementById("txtOut").value = nv;
}
convertByArrayB("101");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Result: <input id="txtOut">