Why are we using [] .join here?

Why do we use [].join()this way?

function printArgs() {
    arguments.join = [].join; 
    var argStr = arguments.join(':'); 
    alert( argStr );
}
printArgs(1, 2, 3);
+4
source share
2 answers

Since an object argumentsis an object similar to Array, but it is not a real array and does not have array properties (for example, joinin your example), except .length. Thus, in your code, you copy the method .joinfrom the array to an object of objects.

+4
source

An object argumentis a local variable array like objectavailable in all functions.

So, arguments.join = [].join;creates a new array and on which you can use all the methods available in the js array.

Therefore var argStr = arguments.join(':');will return1:2:3

var argStr = arguments.join();      // assigns '1,2,3' to argStr 
var argStr = arguments.join(' + '); // assigns '1 + 2 + 3' to argStr
                          // ^ ^       Note empty space here & in assigned value
var argStr = arguments.join('');  // assigns 123 to argStr
0
source

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


All Articles