3

I have a Uint8Array in Javascript that I would like to print the contents of to the console, eg

255, 19, 42, 0

This is my code, which currently prints an empty string

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

I can see the data in the debugger if I set a breakpoint, so bytes is definitely getting filled. When I tried printing via another method, it converted all the bytes to ASCII, but my data is mostly outside of the ASCII printable range.

Is there an equivalent to printf() in JavaScript?

amo
  • 4,082
  • 5
  • 28
  • 42

1 Answers1

10

The concat method doesn't act like a buffer that you can append to, but rather returns a new string.

Therefore, you have to assign the result of concat to your result string on every invocation:

 debugBytes = debugBytes.concat(bytes[i].toString());
 debugBytes = debugBytes.concat(",");

Implemented like this, your debugBytes string will end up containing a comma-separated list of the byte values.


A more concise solution is to convert your Uint8Array to a regular Javascript array, and then use the join method:

console.log(Array.apply([], bytes).join(","));

There's no printf method in the current ECMAScript standard, there are however a number of custom implementations. See this question for some suggestions.

Community
  • 1
  • 1
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • It should be better to `concat` in one time (to reduce method calls): `debugBytes = debugBytes.concat(bytes[i].toString() + ',');`. Or not at all (implicit): `debugBytes += bytes[i].toString() + ',';` – Alejandro Iván Sep 22 '14 at 01:45
  • @AlejandroIván To reduce method calls? What do you think happens when you concatenate strings using `+`? The only thing your alternative does is reduce lines of code, and unfortunately also readability. – Robby Cornelissen Sep 22 '14 at 01:47
  • Well, a `concat` is some sort of array join. So this question says concatenation is faster (due to optimizations): http://stackoverflow.com/questions/7299010/why-is-string-concatenation-faster-than-array-join just saying though. – Alejandro Iván Sep 22 '14 at 01:55
  • A `concat` is not "some sort of array join", and using `+` behaves identical to calling `concat`. – Robby Cornelissen Sep 22 '14 at 01:58