Daniel Näslund
Daniel Näslund

Reputation: 2410

Different result for map() on different arrays

Why do the map() operation generate different output when run on different types of arrays?

I thought literal and obj below were the same type; why do the resulting array differ? Why are the non-literal array concatenated to one element?

Why do the typed array not create an Array of strings, but return the original typed array? Is there a spec requirement that the map operation can't convert a typed array to a different type?

var literal = [1, 2, 3];
var obj = new Array([1, 2, 3]);
var typed = new Uint32Array([1, 2, 3]);


console.log(literal.map(String));
console.log(obj.map(String));
console.log(typed.map(String));

Output

Array [ "1", "2", "3" ] 
Array [ "1,2,3" ]
Uint32Array [ 1, 2, 3 ]

I'm running Firefox 44.0 https://jsfiddle.net/6c8p465r/1/

Upvotes: 0

Views: 365

Answers (1)

KevBot
KevBot

Reputation: 18888

First, using the literal array, or using the Array constructor will produce the same result, but you did not use the constructor correctly.

The following will produce an array inside of the array which is why you get only one array returned to you in string format. So when you call map on this, the entire entry that is being mapped is the internal array.

new Array([1, 2, 3]); // Produces [[1, 2, 3]]

The correct way to create the array the way you want using the Array constructor is to pass in the values as just arguments:

new Array(1, 2, 3); // Produces [1, 2, 3]

The Uint32Array has a couple of things going on with it that have to be understood first.

  1. It holds unsigned integers (can't be converted to a string)
  2. It's constructor is different from the Array constructor

If you check out the Mozilla examples on Uint32Array, you will see that an array of values is expected to be passed into the constructor when using it that way.

Upvotes: 2

Related Questions