简体   繁体   中英

How to convert an array of character codes to string in JavaScript?

I have this function:

function ungarble(garble){
  var s = "";
  for( var i = 0; i < garble.length; i++ ) {
    s += String.fromCharCode(garble[i]);
  }
  return s;
}

It takes in an array of charCodes, then returns a string those charCodes represented.

Does native Javascript have a function that does this?

Note: This is for reading messages returned by child_process.spawn .

fromCharCode already accepts any amount of arguments to convert to a string, so you can simply use apply to give it an array:

 var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]; var str = String.fromCharCode.apply(null, chars); console.log(str);

or using ES6 spread syntax

 var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]; var str = String.fromCharCode(...chars); console.log(str);

How about the reduce function?

 function ungarble(chars) {
    return chars.reduce(function(allString, char) {
        return allString += String.fromCharCode(char);
    }, '');
}

let result = ungarble([65, 66, 67]);

console.log(result) // "ABC"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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