【发布时间】:2020-05-10 01:28:54
【问题描述】:
我正在用 javascript 编写一个十进制到二进制转换器,我遇到了这个问题。
这是我的代码。
function binaryConverter(x)
{
if(x === "")
{
return 0;
}
let binaryArray = new Array(128, 64, 32, 16, 8, 4, 2, 1);
let result = new Array();
let newX;
//pelda: x = 75
for(let i = 0; i < binaryArray.length; i++)
{
if(binaryArray[i] <= x)
{
result.push('1');
newX = x - binaryArray[i]; // 75 - 64 = 11 | 11 - 8 = 3 | 3 - 2 = 1
x = newX;
}
else
{
result.push('0');
}
}
writeBinaryNumber(result);
}
function writeBinaryNumber(ar)
{
for (let i = 0; i < ar.length; i++)
{
document.write(ar[i]);
}
}
使用 document.write() 它是有效的(我只用数字 75 测试过它,我知道二进制代码的第一部分是 0,我会修复它。)。但我想连接我的html。我想返回一个包含数组中字符的变量,但我不能。在带有迭代器的 C++ 中它正在工作,但我不熟悉 javascript,我使用谷歌搜索解决方案,但我找不到。如果有人知道解决方案,请写下来!谢谢!
【问题讨论】:
-
你需要用 in html 右显示
标签: javascript arrays variables converters