Search code examples
javascriptarraysecmascript-6typed-arrays

Using the new ES6 Array.from() method


There's one aspect of the new Array.from method that I'm not understanding. I'm reading the through the Description section on MDN, and came across the following:

Array.from() has an optional parameter mapFn, which allows you to execute a map function on each element of the array (or subclass object) that is being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array. This is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type.

I'm not understanding:

...the intermediate array would necessarily have values truncated to fit into the appropriate type

I'm not sure what this is saying, since we're going from a typed array to a normal Array (using Array.from). It's not like any incorrect types will be in the typed array. Also, the resulting Array from Array.from() will of course accept any type like normal JS arrays do.

Could anyone give insight into what this is trying to say or what I'm missing?


Solution

  • The array subclasses inherit the from method from Array, so you can e.g. call

    const iter = (function*() { for (var i=0; i<512; i++) yield i }());
    const arr = Uint8Array.from(iter);
    console.log(arr); // Uint8Array(512) […, 250, 251, 252, 253, 254, 255, 0, 1, 2, 3, …]
    

    The resulting array is an Uint8Array and has the values truncated respectively. If you provided a mapping function, it would have made a difference whether you used Uint8Array.from(iter, fn) or Uint8Array.from(iter).map(fn).