最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - array.map automatically appends commas when concatenated in a string? - Stack Overflow

programmeradmin0浏览0评论

I am a bit confused by the behavior of 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 a , ?

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

I am a bit confused by the behavior of 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 a , ?

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

Share Improve this question asked Dec 13, 2015 at 10:29 Avijit GuptaAvijit Gupta 5,7563 gold badges23 silver badges35 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 13

Array.map did nothing to your array.

You basically did this

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

Which calls the toString() method of an array, whose default behaviour is to join(',') the array.

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

It is because the arr.map function is returning after processing each element in array and not for individual elements as you are expecting to append to 'result' variable. If you wish to concatenate values to 'result' variable, you should do so inside the map function for each element instead. And as Sirko said, the commas are coming from the toString() method. Check the above code on jsfiddle here: http://jsfiddle.net/qt3nryLq/

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

The commas stem from the toString() method of Array and not 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'
  • MDN on Array.toString()
发布评论

评论列表(0)

  1. 暂无评论