JavaScript等同于PHP的chr()函数 [英] JavaScript equivalent of PHP's chr() function
问题描述
如何将以下代码从PHP转换为JavaScript?
How to transform the following code from PHP to JavaScript?
$str = '';
for ($i = 0; $i < 256; $i++) {
$str .= chr($i);
}
我知道JavaScript中的 String.fromCharCode(n)
与PHP中的 chr(n)
类似,但是当n大于127时,它们似乎返回不同的字符.
I know String.fromCharCode(n)
in JavaScript is similar to chr(n)
in PHP, but it seems they return different characters when n is greater than 127.
推荐答案
PHP的chr()函数将0..127中的输入解释为ascii值,并将128..255中的输入解释为IBM代码页437(CP437,专有扩展ascii)值.这是PHP使用的完整ASCII表: http://www.asciitable.com/
PHP's chr() function interprets input from 0..127 as ascii values and input from 128..255 as IBM code page 437 (CP437, proprietary extended ascii) values. This is the complete ASCII table used by PHP: http://www.asciitable.com/
JavaScript的String.fromCharCode(i)方法将输入解释为UTF-8值,类似于ascii(从0..127开始),而不是IBM CP437扩展ascii(从128..255开始).
JavaScript's String.fromCharCode(i) method interprets input as UTF-8 values, which are similar to ascii (from 0..127) but not the IBM CP437 extended ascii (from 128..255).
您可以尝试在JavaScript中重新创建PHP的chr()函数,例如.G.如下(未试用):
You can try to recreate PHP's chr() function in JavaScript, e. g. as follows (untested):
function chr(n) {
if (n < 128) {
return String.fromCharCode(n);
} else {
return "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "[n - 128];
}
}
这篇关于JavaScript等同于PHP的chr()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!