从二进制到charcode到文本javascript

时间:2017-02-19 18:55:19

标签: javascript binary bonfire fromcharcode

我在freecodecamp的篝火"二元代理商"而我几乎得到了它。它会返回正确的答案但是使用" undefined"首先,我不明白为什么......

function binaryAgent(str) {

var arr = str.split(" ");
var charcoded = [];
var finalStr;

for (var i=0; i<arr.length; i++) {

finalStr += String.fromCharCode((parseInt(arr[i], 2)));

}

return finalStr;

}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

4 个答案:

答案 0 :(得分:1)

您可以初始化变量finalStr以收集带有空字符串''的字符,否则变量的值为undefined并将字符串联到它。

var finalStr = '';

&#13;
&#13;
function binaryAgent(str) {
    var arr = str.split(" "),
        charcoded = [],
        finalStr = '',
        i;

    for (i = 0; i < arr.length; i++) {
        finalStr += String.fromCharCode((parseInt(arr[i], 2)));
    }
    return finalStr;
}

console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111"));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

最简单的方式

function binaryAgent(str) {
    var newStr = str.split(' ').map(item => {
                    return String.fromCharCode(parseInt(item, 2));
                 });
    return newStr.join('');
}

binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

答案 2 :(得分:1)

我就是这样做的:)

function binaryAgent(str) {
      str = str.split(" ");
      var  final = '';

      for (var i = 0; i < str.length; i++) {
          final += String.fromCharCode((parseInt(str[i], 2)));
      }
      return final;
    }

    binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");

答案 3 :(得分:0)

这就是我如何进行“二进制代理人”挑战

function binaryAgent(str) {
    return str.split(" ").map((x) => x = String.fromCharCode(parseInt(x, 2))).join("");
}