The map method in JavaScript

Source: Internet
Author: User
Tags javascript array

Suppose that there is a function f (x) =x2; the function is in an array [1,2,3,4,5,6,7,8,9], which is usually implemented by means of traversal.

function f (x) {  return x * x;   } var arr = [1,2,3,4,5,6,7,8,9]; var result = [];  for (var i=0; i<arr.length; i++) {Result.push (f (arr[i))   }

This can be done, but we have a more elegant implementation.

function f (x) {    return x * x;} var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9//  [1, 4, 9, +, +, +, +, +, Bayi]

The map () method is defined in the JavaScript array, we call the map () method of array and pass in our own function, and we get a new array as the result. The map passes in the parameters F, which is the function itself.

So, map (), as a higher-order function, actually abstracts the arithmetic rules. So we can not only calculate the simple f (x) =x2, but also the arbitrary complexity of the function, such as the array of all the numbers into a string:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9//  [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']
    

The map method in JavaScript

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.