[英]How to convert an array of character codes to string in JavaScript?
我有这个功能:
function ungarble(garble){
var s = "";
for( var i = 0; i < garble.length; i++ ) {
s += String.fromCharCode(garble[i]);
}
return s;
}
它接受一个 charCodes 数组,然后返回这些 charCodes 表示的字符串。
本机 Javascript 是否具有执行此操作的功能?
注意:这是用于读取child_process.spawn
返回的child_process.spawn
。
fromCharCode
已经接受任何数量的参数来转换为字符串,所以你可以简单地使用apply
给它一个数组:
var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]; var str = String.fromCharCode.apply(null, chars); console.log(str);
或使用ES6 扩展语法
var chars = [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]; var str = String.fromCharCode(...chars); console.log(str);
reduce 函数呢?
function ungarble(chars) {
return chars.reduce(function(allString, char) {
return allString += String.fromCharCode(char);
}, '');
}
let result = ungarble([65, 66, 67]);
console.log(result) // "ABC"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.