遍历具有二进制数字的数组,如果数字为1,则写true;如果数字为0,则写false

时间:2018-10-03 01:48:58

标签: javascript arrays

我试图通过首先在ascii中解析单个字符,然后将ascii解析为二进制,然后将二进制放入数组,来制作一个通过字母加密的网页。将其放入数组后,我必须遍历该数组并为“ 1”写为true或为“ 0”写false。然后,我必须输出到页面。例如,如果输入字母“ a”,输出结果将是“ false,true,true,false,false,false,false,true”

更新:为了解决我的问题,我添加了“循环”

    $(document).ready(function()
{
    var output = document.getElementById("output");
    var strQuestion = "Enter ONE character, matey!";
    var strStandard = "J";
    var chrCharacter = "";
    var chrLength = 0;
    var array = [];
    var arrayLength = 0;
    while (chrLength != 1)
    {
    chrCharacter = prompt(strQuestion, strStandard);
    chrLength = chrCharacter.length;
    }
    intAscii = parseAscii(chrCharacter);

    strBin = parseBin(intAscii);

    array = strBin.split("");

        for (i = 0; i < arrayLength; i++ )
        {
         if (array[i] = 0)
          {
          array[i] = false;
          }
         else if (array[i] = 1)
          {
          array[i] = true;

        }

}



    output.innerHTML = array;




    }); //end document.ready



    /*****          
    Purpose: Converts a character into ascii        
    Parameters: single character / letter       
    Return: integer representing an ascii value
    *****/
    function parseAscii(chrCharacter)
    {
        intAscii = chrCharacter.charCodeAt(0);
        return intAscii;
    }

    /*****          
    Purpose: Takes the ascii code and turns it into binary          
    Parameters: single integer representing an ascii value  
    Return: binary, base 2 representation of the number passed to this function
    *****/
    function parseBin(intAscii)
    {
        strBin = parseInt(intAscii, 10).toString(2);
        if(strBin.length < 8)
        {
            var intPlaceHolders = 8 - strBin.length;
            for(var i = 0; i < intPlaceHolders; i++)
            {
                strBin = "0" + strBin;
            }

        }

        return strBin;
    }

2 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,则可以使用map函数并使用innerHTML将输出的1和0(二进制)数组转换为ture和false值,以将输出添加到DOM :

请参见以下示例:

// Populate myBinaryArray using your ascii method to get the follow:
let myBinaryArray = [1, 0, 0, 1, 1, 0, 1];
document.body.innerHTML += myBinaryArray.map(bit => !(!bit));

答案 1 :(得分:0)

我会将包含二进制文件的数组转换为具有布尔值的数组,但您可以将它们连接在一起,成为可以在网页上显示的字符串。

array = [1,1,0,0,1]

// This will map over the items and perform an type conversion 
var booleanArray = array.map(Boolean)

// Join all the items together as a string
Var booleanString = booleanArray.join(", ")

output.innerHTML = booleanString

`

我没有测试它,但是如果我没有任何错字,它应该可以工作。


顺便说一句,我不认为这就是他们对循环的重视。但这绝对是完成工作的一种方式。