This question already has an answer here:
这个问题在这里已有答案:
- Converting byte array to string in javascript 5 answers
- 在javascript 5答案中将字节数组转换为字符串
I am getting a response from a SOAP server and it is an array of bytes, fixed size.
我从SOAP服务器获得响应,它是一个固定大小的字节数组。
For instance, I get { rsp: { errorNumber: '1', errorMessage: { item: [Object] } } }
例如,我得到{rsp:{errorNumber:'1',errorMessage:{item:[Object]}}}
[ '73',
'110',
'118',
'97',
'108',
'105',
'100',
'32',
'112',
'97',
'115',
'115',
'119',
'111',
'114',
'100',
'0']
How do I turn that array to a string it javascript?
如何将该数组转换为javascript的字符串?
3 个解决方案
#1
3
Each "byte" in your array is actually the ASCII code for a character. String.fromCharCode
will convert each code into a character.
数组中的每个“字节”实际上是字符的ASCII代码。 String.fromCharCode会将每个代码转换为一个字符。
It actually supports an infinite number of parameters, so you can just do:
它实际上支持无数个参数,所以你可以这样做:
String.fromCharCode.apply(String, arr);
When ran on your array you get: "Invalid password"
.
在您的阵列上运行时,您会收到:“密码无效”。
As @Ted Hopp points out, the 0
at the end is going to add a null character to the string. To remove it, just do: .replace(/\0/g,'')
.
正如@Ted Hopp指出的那样,最后的0将为字符串添加一个空字符。要删除它,只需执行:.replace(/ \ 0 / g,'')。
String.fromCharCode.apply(String, arr).replace(/\0/g,'');
#2
2
Here is what you want, the String.fromCharCode
function:
这是你想要的,String.fromCharCode函数:
var foo = [
'73',
'110',
'118',
'97',
'108',
'105',
'100',
'32',
'112',
'97',
'115',
'115',
'119',
'111',
'114',
'100',
'0'];
var str = '';
for (var i=0; i<foo.length; ++i) {
str+= String.fromCharCode(foo[i]);
}
console.log(str);
Or better :
或更好 :
var str = String.fromCharCode.apply(null, foo);
#3
2
Here's one more alternative using map:
这是使用地图的另一种选择:
var str = arr.map(String.fromCharCode).join("");
#1
3
Each "byte" in your array is actually the ASCII code for a character. String.fromCharCode
will convert each code into a character.
数组中的每个“字节”实际上是字符的ASCII代码。 String.fromCharCode会将每个代码转换为一个字符。
It actually supports an infinite number of parameters, so you can just do:
它实际上支持无数个参数,所以你可以这样做:
String.fromCharCode.apply(String, arr);
When ran on your array you get: "Invalid password"
.
在您的阵列上运行时,您会收到:“密码无效”。
As @Ted Hopp points out, the 0
at the end is going to add a null character to the string. To remove it, just do: .replace(/\0/g,'')
.
正如@Ted Hopp指出的那样,最后的0将为字符串添加一个空字符。要删除它,只需执行:.replace(/ \ 0 / g,'')。
String.fromCharCode.apply(String, arr).replace(/\0/g,'');
#2
2
Here is what you want, the String.fromCharCode
function:
这是你想要的,String.fromCharCode函数:
var foo = [
'73',
'110',
'118',
'97',
'108',
'105',
'100',
'32',
'112',
'97',
'115',
'115',
'119',
'111',
'114',
'100',
'0'];
var str = '';
for (var i=0; i<foo.length; ++i) {
str+= String.fromCharCode(foo[i]);
}
console.log(str);
Or better :
或更好 :
var str = String.fromCharCode.apply(null, foo);
#3
2
Here's one more alternative using map:
这是使用地图的另一种选择:
var str = arr.map(String.fromCharCode).join("");