JS中数据转换为UTF16
时间: 2024-05-14 19:18:09 浏览: 4
在JavaScript中,可以使用String.prototype.charCodeAt()方法获取字符串中每个字符的UTF-16代码单元值,也可以使用String.fromCharCode()方法将UTF-16代码单元值转换为字符。
例如,下面的代码将字符串转换为UTF-16代码单元值数组:
```
function stringToUTF16Array(str) {
const utf16Array = [];
for (let i = 0; i < str.length; i++) {
const code = str.charCodeAt(i);
utf16Array.push(code);
}
return utf16Array;
}
const str = "Hello, world!";
const utf16Array = stringToUTF16Array(str);
console.log(utf16Array); // [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
```
可以使用String.fromCharCode()方法将UTF-16代码单元值数组转换为字符串:
```
function UTF16ArrayToString(utf16Array) {
let str = "";
for (let i = 0; i < utf16Array.length; i++) {
const code = utf16Array[i];
str += String.fromCharCode(code);
}
return str;
}
const utf16Array = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33];
const str = UTF16ArrayToString(utf16Array);
console.log(str); // "Hello, world!"
```