Search code examples
javascriptarraysmutation

Why don't javascript function join() work?


I have an array named res2 looks like below

[ ' sh', '1119', '' ]

My purpose is to join these elements into one element. So I joined it

res2.join();

but it didn't work

[ ' sh', '1119', '' ]

Anyone knows the reason and solution for the situation?


Solution

  • Array.prototype.join() will not mutate the original array, but it will return a new string:

    var res2 = [ ' sh', '1119', '' ];
    var result = res2.join(); //" sh,1119,"
    //res2 is still the array