javascript - How does the Math.max.apply() work? -
how math.max.apply() work?.
<!doctype html> <html> <head> <meta charset=utf-8 /> <title>js bin</title> </head> <body> <script> var list = ["12","23","100","34","56", "9","233"]; console.log(math.max.apply(math,list)); </script> </body> </html> https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/math/max
the above code finds max number in list. can tell me how below code work?. seems works if pass null or math.
console.log(math.max.apply(math,list)); does user-defined/native functions have call , apply method can use?.
apply accepts array , applies array parameters actual function. so,
math.max.apply(math, list); can understood as,
math.max("12", "23", "100", "34", "56", "9", "233"); so, apply convenient way pass array of data parameters function. remember
console.log(math.max(list)); # nan will not work, because max doesn't accept array input.
there advantage, of using apply, can choose own context. first parameter, pass apply of function, this inside function. but, max doesn't depend on current context. so, work in-place of math.
console.log(math.max.apply(undefined, list)); # 233 console.log(math.max.apply(null, list)); # 233 console.log(math.max.apply(math, list)); # 233 since apply defined in function.prototype, valid javascript function object, have apply function, default.
Comments
Post a Comment