1

related to this question: Javascript worker.postMessage shrinks empty array

When an array that contains undefined elements is given to Worker.prototype.postMessage the array that arrives has been messed with. It's length remains the same, but it is no longer possible to iterate using .map, .reduce, for...in etc.

The below code outputs 2 0. Is this a bug, or is it somehow expected behavior? The same happens if you pass an array with partial values [undefined, 2] or [1, undefined] for example.

var response = "self.onmessage=function(msg){console.log(msg.data.length, msg.data.reduce(function(i){return ++i;},0))}";

var blob = new Blob([response], {type: 'application/javascript'});
var worker = new Worker(URL.createObjectURL(blob))
worker.postMessage([undefined, undefined])
Community
  • 1
  • 1
Zack Newsham
  • 2,810
  • 1
  • 23
  • 43
  • I suggest that you define worker function as a function and then convert it to string. That makes code much more readable, see here: http://stackoverflow.com/a/33432215/607407 – Tomáš Zato Aug 05 '16 at 10:33
  • Also, how is this question different than the related one. Could you clarify? I can confirm this happens in google chrome and not firefox. If you cannot clarify what are you asking that wasn't already asked this question should be closed as a duplicate. – Tomáš Zato Aug 05 '16 at 10:46
  • @TomášZato, the related question defines a `new Array(2)` which gets collapsed to an actual empty array `[]`. This was what happened when I tried removing the `new Array(2)` and replacing it with `[undefined, undefined]` it gets collapsed into an array with length = 2, but no indicies. – Zack Newsham Aug 05 '16 at 13:08

0 Answers0