繁体   English   中英

JavaScript:如何将数组 [char] 值存储到变量中?

[英]JavaScript: How to store array[char] values into a variable?

我正在用 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,我使用谷歌搜索解决方案,但我找不到。 如果有人知道解决方案,请写下来! 谢谢!

使用数组join()方法将数组中的所有字符串连接成一个字符串。

let binaryString = ar.join('');

您也可以只连接到一个字符串而不是创建一个数组。

 function binaryConverter(x) { if (x === "") { return 0; } let binaryArray = new Array(128, 64, 32, 16, 8, 4, 2, 1); let result = ''; let newX; //pelda: x = 75 for (let i = 0; i < binaryArray.length; i++) { if (binaryArray[i] <= x) { result += '1' newX = x - binaryArray[i]; // 75 - 64 = 11 | 11 - 8 = 3 | 3 - 2 = 1 x = newX; } else { result += '0'; } } return result; } document.getElementById("input").addEventListener("change", function() { var input = parseInt(this.value); document.getElementById("result").innerText = binaryConverter(input); })
 Enter number: <input id="input"> <br> Result: <span id="result"></span>

你可以这样做

document.getElementById('demo').innerHTML = ar.join('')

 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); } binaryConverter(75) function writeBinaryNumber(ar) { document.getElementById('demo').innerHTML = ar.join('') }
 #demo{ color:red }
 <p id="demo" ></p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM