繁体   English   中英

如何使用JavaScript将ASCII数字数组转换回其char值?

[英]How can I convert an Array of ASCII numbers back to their char value using JavaScript?

我已经使用string.charCodeAt()将字符串转换为它们的ascii,但是现在我已经完成了添加/减去值的工作,我想将它们从ASCII转换回字母和字符串。

我希望将以下数组转换回其char字母,并最终使用JavaScript转换为字符串。

 asciiKeys= [70, 69, 69, 69, 32, 67, 66, 68, 69, 32, 67, 65, 77, 67];

我尝试使用以下内容,但始终表明它不是函数:

for (var j=0;j<str.length;j++){
    newAsciikeys.push(asciiKeys[j].fromCharCode(0));
}

fromCharCodeString上的静态函数。 因此,这将满足您的需要,而无需循环:

reconstituted = String.fromCharCode.apply(null, asciiKeys);

apply函数是一种将一系列项发送到函数的方式,就像您手动键入每个参数一样。 例如, String.fromCharCode( asciiKeys[0], asciiKeys[1], asciiKeys[2], asciiKeys[3], ... )

(请注意,我假设您不需要中间字符数组,并且此解决方案直接进入您请求的最终字符串。如果您还想要中间字符数组,则可以使用reconstituted.split('')拆分结果数组reconstituted.split('') 。)

编辑:(感谢@Kaiido)

为了稳健起见,请注意.apply对于它可以处理的参数数量(读取:数组大小)具有JS引擎特定的限制。 要处理这些情况,请考虑分拆工作 ,或通过一对一处理退回到值得信赖的旧循环。

数组中的值需要传递给.fromCharCode() ; .fromCharCode()不是.charCodeAt()

String.fromCharCode.apply(String, asciiKeys)

或者,您可以使用TextDecoder()将array的ArrayBuffer表示形式转换为字符串。 如果预期结果是数组,则可以使用spread元素将字符串转换为数组。

 var asciiKeys = [70, 69, 69, 69, 32, 67, 66, 68, 69, 32, 67, 65, 77, 67]; var str = new TextDecoder().decode(Uint8Array.from(asciiKeys)); console.log(str, [...str]); 

在现代浏览器(不是IE)上,可以使用Spread语法将其缩短:

 s = "ABC", j = JSON.stringify a = [...s].map(s => s.charCodeAt()) // string to array ( [...s] is short for s.slice() ) r = String.fromCharCode(...a) // array to string ( (...a) is short for .apply(0, a) ) console.log(j(s), j(a), j(r)) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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