Math.min.apply(0, array) - why?

后端 未结 4 1168
情话喂你
情话喂你 2020-12-13 13:31

I was just digging through some JavaScript code (Raphaël.js) and came across the following line (translated slightly):

Math.min.apply(0, x)

4条回答
  •  难免孤独
    2020-12-13 13:40

    The reason is this:

    • Your input x is an array

    • The signature of Math.min() doesn't take arrays, only comma separated arguments

    • If you were using Function.prototype.call() it would have almost the same signature, except the first argument is the this context, i.e. who's "calling"

      • Example: Math.min.call(context, num1, num2, num3)
    • The context only matters when you refer to this inside the function, e.g. most methods you can call on an array: Array.prototype. would refer to this (the array to the left of the 'dot') inside the method.

    • Function.prototype.apply() is very similar to .call(), only that instead of taking comma-separated arguments, it now takes an array after the context.

      • Function.prototype.call(context, arg1, arg2, arg3)
      • Function.prototype.apply(context, [arg1, arg2, arg3])
    • The 0 or null that you put in as the first argument is just a place shifter.

提交回复
热议问题