在JavaScript上将整数数组转换为字符串 [英] Convert integer array to string at javascript

查看:73
本文介绍了在JavaScript上将整数数组转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是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;

输出为:中文chinese

这是JavaScript代码:

Here is javascript code:

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);

输出为:中æchinese

那么我应该如何使用javascript处理数组?

So how should I process the array at javascript?

推荐答案

JavaScript字符串由 UTF- 16 代码单元,但是数组中的数字是 UTF-8 字符串.这是一种转换字符串的方法,该方法使用 decodeURIComponent() 函数:

JavaScript strings consist of UTF-16 code units, yet the numbers in your array are the bytes of a UTF-8 string. Here is one way to convert the string, which uses the decodeURIComponent() function:

var i, str = '';

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

以传统方式执行从UTF-8到UTF-16的转换可能会更高效,但需要更多代码.

Performing the UTF-8 to UTF-16 conversion in the conventional way is likely to be more efficient but would require more code.

这篇关于在JavaScript上将整数数组转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆