我在Javascript中有一个Uint8Array,我想打印到控制台的内容,例如
255, 19, 42, 0
这是我的代码,目前打印一个空字符串
var bytes = new Uint8Array(data);
var debugBytes = "";
for(var i=0; i<bytes.byteLength; i++) {
debugBytes.concat(bytes[i].toString());
debugBytes.concat(",");
}
console.log('Processing packet [' + bytes[1] + '] ' + debugBytes);
如果设置断点,我可以在调试器中看到数据,所以字节肯定会被填满。当我尝试通过另一种方法打印时,它将所有字节转换为ASCII,但我的数据大多数在ASCII可打印范围之外。
JavaScript中是否有与printf()等效的内容?
答案 0 :(得分:4)
concat
方法不像你可以附加的缓冲区那样,而是返回一个新字符串。
因此,您必须在每次调用时将concat
的结果分配给结果字符串:
debugBytes = debugBytes.concat(bytes[i].toString());
debugBytes = debugBytes.concat(",");
如此实现,您的debugBytes
字符串最终将包含以逗号分隔的字节值列表。
更简洁的解决方案是将您的Uint8Array
转换为常规Javascript数组,然后使用join
方法:
console.log(Array.apply([], bytes).join(","));
当前ECMAScript标准中没有printf
方法,但是有许多自定义实现。有关建议,请参阅此question。