Does Array.map automatically add commas when concatenating in a string?

I am a little confused by the behavior of the Array.map function here:

 var arr = ['one', 'two', 'three']; var result = ''; result += arr.map(function(elm) { return elm; }); // 'one,two,three' 

How does it automatically join the returned results with,?

Note. This only happens if I concatenate the return result in a string.

+5
source share
3 answers

Array.map did nothing for your array.

You basically did it

 '' + ['one', 'two', 'three'] 

Which calls the toString() method for an array whose default behavior is the join(',') array.

+10
source
 var arr = ['one', 'two', 'three']; var result = ''; var r = arr.map(function(elm) { result = result + ' ' + elm; return elm; }); alert('r-> ' + r); alert('result-> ' + result); 

This is because the arr.map function is returned after processing each element in the array, and not for individual elements, since you expect to add "result" to the variable. If you want to combine the values ​​into a result variable, you must do this inside the map function for each element. And, as Sirko said, commas come from the toString () method. Check out the jsfiddle code above here: http://jsfiddle.net/qt3nryLq/

Link to Array.map (): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

+2
source

The wrists are based on the toString() method of Array , not on the map() function!

 var arr = ['one', 'two', 'three']; arr.toString(); // 'one,two,three' var result = ''; result += arr.map(function(elm) { return elm; }); result.toString(); // 'one,two,three' 
+1
source

Source: https://habr.com/ru/post/1238009/


All Articles