简体   繁体   English

在javascript中将整数数组转换为字符串

[英]Convert integer array to string at javascript

Here is php code:这是php代码:

$arr=array(228,184,173,230,150,135,99,104,105,110,101,115,101);
$str='';
foreach ($arr as $i){
    $str.=chr($i);
}
print $str;

the output is:中文chinese输出为:中文chinese

Here is javascript code:这是javascript代码:

var arr=[228,184,173,230,150,135,99,104,105,110,101,115,101];
var str='';
for (i in arr){
    str+=String.fromCharCode(arr[i]);
}
console.log(str);

the output is: ä¸æchinese输出为: ä¸æchinese

So how should I process the array at javascript?那么我应该如何在javascript中处理数组呢?

JavaScript strings consist of UTF-16 code units, yet the numbers in your array are the bytes of a UTF-8 string. JavaScript 字符串由UTF-16代码单元组成,但数组中的数字是UTF-8字符串的字节。 Here is one way to convert the string, which uses the decodeURIComponent() function:这是转换字符串的一种方法,它使用decodeURIComponent()函数:

var i, str = '';

for (i = 0; i < arr.length; i++) {
    str += '%' + ('0' + arr[i].toString(16)).slice(-2);
}
str = decodeURIComponent(str);

Performing the UTF-8 to UTF-16 conversion in the conventional way is likely to be more efficient but would require more code.以传统方式执行 UTF-8 到 UTF-16 转换可能更有效,但需要更多代码。

var arry = [3,5,7,9];
console.log(arry.map(String))

the result will be ['3','5','7','9']结果将是['3','5','7','9']

var arry = ['3','5','7','9']
console.log(arry.map(Number))

the result will be [3,5,7,9]结果将是[3,5,7,9]

Another solution without decodeURIComponent for characters up to 3 bytes (U+FFFF).另一个没有decodeURIComponent解决方案,用于最多 3 个字节 (U+FFFF) 的字符。 The function presumes the string is valid UTF-8, not much error checking...该函数假定字符串是有效的 UTF-8,没有太多的错误检查......

function atos(arr) {
    for (var i=0, l=arr.length, s='', c; c = arr[i++];)
        s += String.fromCharCode(
            c > 0xdf && c < 0xf0 && i < l-1
                ? (c & 0xf) << 12 | (arr[i++] & 0x3f) << 6 | arr[i++] & 0x3f
            : c > 0x7f && i < l
                ? (c & 0x1f) << 6 | arr[i++] & 0x3f
            : c
        );

    return s
}

Seems the best way these days is the following:这些天似乎最好的方法如下:

function bufferToString(arr){
    return arr.map(function(i){return String.fromCharCode(i)}).join("")
}

Chinese charset has a different encoding in which one char is more than one byte long.中文字符集有一种不同的编码,其中一个字符的长度超过一个字节。 When you do this当你这样做时

for (i in arr){
    str+=String.fromCharCode(arr[i]);
}

You are converting each byte to a char(actually string) and adding it to a string str.您正在将每个字节转换为字符(实际上是字符串)并将其添加到字符串 str 中。 What you need to do is, pack the bytes together.您需要做的是,将字节打包在一起。

I changed your array to this and it worked for me:我把你的数组改成了这个,它对我有用:

var arr=[20013,25991,99,104,105,110,101,115,101];

I got these codes from here .我从这里得到这些代码。

you can also take a look at this for packing bytes to a string.您还可以查看this将字节打包为字符串。

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

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