The Magical magic of apply

Source: Internet
Author: User

There is a very common question, "what is the difference between call and apply?" "Everyone knows the answer: they differ only in the way they accept parameters, the second argument passed to call must be enumerated, and the second argument passed to apply is an array, as follows

function sum (num1,num2) {  return num1 + num2;} function Callsum (num1,num2) {  return sum.call (this, num1,num2);} function Applysum (num1,num2) {  return sum.apply (this, [num1,num2]);   // or return sum.apply (this,arguemnts);}

That is, the Apply function actually has a function: to convert the passed-in parameter array into the form of a parameter list, passing through. With this feature of apply, many operations can be simplified.

(1) Find the maximum/minimum value in the array

var arr = [1,2,3,4,5];console.log (Math.max.apply (null, arr)); // 5   Apply Method Console.log (Math.max (1,2,3,4,5)); // 5     Original Method

1) Both methods in the above code are implemented to find the maximum value, but if the array is long or only arr (not know the specific values), the original method will be cumbersome (to column a long number, or require the array to be converted to a list first), and the Apply method directly apply its own conversion function, It's easy to implement.

2) The first parameter in the Apply method is null, because there is no object to invoke apply, we just need to use this method to help calculate the line.

(2) merging of two arrays

var = [arr1]var arr2 = [4,5,6]; Array.prototype.push.apply (ARR1,ARR2); Console.log (arr1); // [1,2,3,4,5,6]

To implement the array merging is also troublesome, according to the above method to arr1 call apply, you can simply put arr2 in order to merge into the array arr1.

Summary: The above two usages all have one thing in common, that is, you need to convert the array into a list form, and apply just can do this function.

The Magical magic of apply

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.