3

When I call:

var result = inputs.map(function(){ return $(this).val(); });

result contains an array like:

['foo', 'bar', 'buz']

I want to join result:

result.join(', ');

works, but

var result = inputs.map(function(){ return $(this).val(); }).join(', ');

gives

TypeError: undefined is not a function

My question is rather theoretically - why cannot I access result array in a chain and I have to assign it to the variable before working on the result ?

hsz
  • 148,279
  • 62
  • 259
  • 315

2 Answers2

4

The result of jQuery's .map method is not an array, it's a jQuery collection. Use .get() to return an array of the collection contents.

var result = inputs.map(function(){ return $(this).val(); }).get().join(', ');
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks - indeed the type of result is `object` but console displays it as an array. – hsz May 23 '14 at 08:19
  • Yeah, jQuery makes its collections look like arrays in the console. It confused me the first time I ran into this. – Barmar May 23 '14 at 08:21
1

Because the returned value is a jQuery wrapped array which doesn't have join method, you should get the array using jQuery get method.

This is a related question.

Community
  • 1
  • 1
Ram
  • 143,282
  • 16
  • 168
  • 197