从二进制到字符码再到文本 javascript

From binary to charcode to text javascript

我在 freecodecamp 的篝火中 "binary agents" 我几乎明白了。它 returns 是正确答案,但首先是 "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");

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

var finalStr = '';

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"));

最简单的方法

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");

我就是这样做的:)

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");

我就是这样"Binary Agents"挑战

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