Skip to content
Advertisement

array.push.apply to implment ‘concat’ with explain

Learning reactive programming and encouter this bit of code,

JavaScript

understand apply

FULL CODE

JavaScript

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

but when this code appear and get my head spinning. it’s pretty much doing the concat. can someone please explain?

many thanks

Advertisement

Answer

some_function.apply(obj, [a, b, c])

is (basically…) the same as:

obj.some_function(a, b, c)

Which is: “invoke the function, referenced by ‘some_function’, with ‘obj’ as the ‘this argument’, and the list of parameters as parameters”.

That is, calling the function (in your case, ‘push’) as if it was a member of ‘obj’ (in you case ‘results’).

See: Function.prototype.apply for details.

An example to play around with:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement