You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Buffer转字符串后map方法展示关键词异常问题求助

问题解决:Buffer处理UTF-16LE字节数组导致的字符串异常

问题根源

你的关键词字节数组是UTF-16LE编码(每个可见字符后跟一个0字节,比如79,0对应字符'O'),直接用默认的buffer.toString()(utf8编码)解码时,会把0字节解析成不可见的空字符\x00。这些隐藏的空字符肉眼看不到,但会导致后续字符串处理(比如split、传递到主函数)出现异常,最终让map渲染失效。

解决方案

1. 正确解码字节数组

指定用utf16le编码解码,直接得到无隐藏空字符的干净字符串:

const Keywords = [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110, 0, 59, 0];
const buffer = Buffer.from(Keywords);
// 用utf16le解码,得到正常字符串
const bufferString = buffer.toString('utf16le'); // 输出:"Obst;Person;"

2. 处理split后的空元素

split(";")会生成末尾的空字符串,用filter(Boolean)过滤掉无效项:

const words = bufferString.split(";").filter(Boolean); // 输出:["Obst", "Person"]

3. 验证并传递数组

此时得到的words数组和手动创建的完全一致,传递到主函数用map渲染就能正常显示所有关键词。

完整验证代码

const Keywords = [79, 0, 98, 0, 115, 0, 116, 0, 59, 0, 80, 0, 101, 0, 114, 0, 115, 0, 111, 0, 110, 0, 59, 0];
const buffer = Buffer.from(Keywords);
const bufferString = buffer.toString('utf16le');
const words = bufferString.split(";").filter(Boolean);

// 主函数中map渲染示例
words.map(word => console.log(word));
// 输出:
// Obst
// Person

内容的提问来源于stack exchange,提问作者Broump

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:10:29