How is "[]" used specifically as a parameter?

I did some javascript exercises online (codewars.com). One of the problems asked the user to take an array of array objects and remove one level from the entire array.

[] /* becomes */ [] [[1, 2, 3], ["a", "b", "c"], [1, 2, 3]] /* becomes */ [1, 2, 3, "a", "b", "c", 1, 2, 3] [[3, 4, 5], [[9, 9, 9]], ["a,b,c"]] /* becomes */ [3, 4, 5, [9, 9, 9], "a,b,c"] 

I ended up learning about the concat method, but the most popular solution used this operator ...

 function (arr){ return [].concat.apply([],arr); } 

Can someone explain the use of [] ? I can’t understand how this gives the correct results (and this does not give an explanation on the page). I know that there are many other cases where empty brackets are used as parameters and marking arrays, so understanding the usage here may help me in the future use it in the future.

+7
javascript arrays
source share
1 answer

Allows you to break it into several lines, so that it is easier to describe. The description of line D in particular is what answers your question

 [] // A .concat // B .apply( // C [], // D arr // E ); 
  • A Is an array, but here it is simply used as a shorthand for Array.prototype so that we can access ..
  • B concat from Array.prototype
  • C , which we then invoke (using apply ) with
  • D this argument of the new array, which will be the base object and
  • E argument list, which was our previous arr

So you can rewrite this with Array.prototype and call as

 var new_base_arr = []; Array.prototype.concat.call( new_base_arr, arr[0], arr[1], ... arr[n] ); 

What may seem more familiar to you, written as

 new_base_arr.concat(arr[0], arr[1], ..., arr[n]); 

The problem solved here calls a function with an indefinite number of arguments.

+7
source share

All Articles