Use the parameter array of apply to improve the elegance and efficiency of the Code

Source: Internet
Author: User

Use the parameter array of apply to improve the elegance and efficiency of the Code

Function.apply () Tips for improving program performance

Let's start with the Math.max () function, the Math.max can be followed by any parameter, and finally the maximum value in all parameters is returned.

Like what
Alert (Math.max (5,8))//8
Alert (Math.max (5,7,9,3,1,6))//9

But in many cases, we need to find the largest element in the array.
var arr=[5,7,9,1]
Alert (Math.max (ARR))//This is not possible. It must be written like this.

function Getmax (arr) {
var arrlen=arr.length;
for (Var i=0,ret=arr[0];i<arrlen;i++) {
Ret=math.max (Ret,arr[i]);
}
return ret;
}

It's troublesome and inefficient to write. If you use apply, look at the code:
function GetMax2 (arr) {
Return Math.max.apply (Null,arr);
}
The two pieces of code achieve the same goal, but GETMAX2 is elegant, efficient, and much simpler.

Use the parameter array of apply to improve the elegance and efficiency of the Code

Related Article

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.