The clever use of Javascript apply

Source: Internet
Author: User

Math.max can be implemented to get the largest item in the array
var array = [1,2,3,4,5]; var max = Math.max.apply (null//  5

Called when the first parameter gave a null, this is because there is no object to call this method, only need to use this method to help the operation, to get the result returned on the line, so directly passed a null past.

Math.min can be implemented to get the smallest item in the array
var array = [1,2,3,4,5]; var min= Math.min.apply (null, array); Console.log (min); 1
Add the Max and Min method above the native object

Then you'll need to use the native object method the Object.defineproperty () method defines a new property directly on an object, or modifies an existing property of an object and returns the object.

Add a method above the native object, and the for loop will not find the

Object.defineproperty (Array.prototype, ' Max '), {writable:false, Enumerable:false, Configurable:true, Value:function () {              returnMath.max.apply (NULL, This);            }      }); Object.defineproperty (Array.prototype,' Min ', {writable:false, Enumerable:false, Configurable:true, Value:function () {              returnMath.min.apply (NULL, This);  }      }); 

How to use it, call it directly on the array

var arr = [54,545,2165,545,56];  Console.log (Arr.max ());  

Clever usage of Javascript apply

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.