Apply method don't have him!

Source: Internet
Author: User

The first is apply () a very powerful function-- can be an array by default into a parameter list!!!

Application:

1. Find the maximum value in an array

var arr= [1, 3, 3, 6];    var max =math.max.apply (null, arr);    Alert (max);    6   

The Math.max () method accepts multiple arguments, but does not accept the array, so the direct Math.max (arr) is not able to achieve the effect, and the array is converted to the parameter list by apply ().

2. Merging arrays

① using the Concat () method

var arr1 = [1, 3, 3, 6];    var arr2 = [2, 4, 5, 6];    var arr = Arr1.concat (arr2); alert (arr);//[1,3,3,6,2,4,5,6]    

The concat () method does not change the original array, only a new array is returned.

② Loop Traversal Insert

var arr1 = [1, 3, 3, 6];     var arr2 = [2, 4, 5, 6];     var arr2len = arr2.length;      for (var i=0; i<arr2len; i++) {        arr1.push (arr2[i]);    }    alert (arr1);    [1,3,3,6,2,4,5,6] 

③apply () method

var arr1 = [1, 3, 3, 6];     var arr2 = [2, 4, 5, 6];     var arr =  Array.prototype.push.apply (arr1, arr2);    Alert (arr);      8    alert (arr1);     [1,3,3,6,2,4,5,6] 

Inserts the contents of the ARR2 directly into the arr1, and the expression return value is the length of the array.

Apply method don't have him!

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.