Apply to convert an array into a parameter list

Source: Internet
Author: User

Apply can convert an array by default to a list of arguments ([param1,param2,param3] to PARAM1,PARAM2,PARAM3) This is if we use a program to implement each item of the array, to replace the list of parameters.

1.math.max gets the largest item in the array

Because the Math.max parameter does not support Math.max ([PARAM1,PARAM2]), which is the array

But it supports Math.max (param1,param2,param3 ...), so you can solve the var max=math.max.apply (Null,array) According to the characteristics of the just apply. It's so easy to get one of the largest items in an array

(Apply will change a number assembly to a parameter by passing it to a method)

Note: This block is called when the first parameter gives a null, this is because there is no object to call this method, I just need to use this method to help me to calculate the return of the results on the line. So I passed a null pass directly.

2.math.min can be implemented to get the smallest item in the array

Likewise and Max is a thought var min=math.min.apply (Null,array);

3.array.prototype.push can implement two array merges

The same push method does not provide an array of push, but it provides push (Param1,param,... paramn) So it is also possible to replace this array with apply, namely:

var arr1=New Array ("1","2","3");

var arr2=New Array ("4","5","6");

Array.prototype.push.apply (ARR1,ARR2);

It can also be understood that arr1 invokes the push method, which converts the array to a collection of parameter lists through apply.

Under what circumstances, you can use a special usage like math.min and so on:

In general, the target function requires only n argument lists, not the form of an array ([param1[,param2[,... [, Paramn]]] ), you can solve this problem skillfully by apply way!

Apply to convert an array into a parameter list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.