Questions about callback function parameters in the map method of array

Source: Internet
Author: User

To get to the point, let's look at two examples first.

var arr=[' 1 ', ' 4 ', ' 9 ', ' 16 '];

var (MATH.SQRT);

Guess what the result of R would be?

That's right.


Let's try another one.

var arr=[' 1 ', ' 4 ', ' 9 ', ' 16 '];

var (parseint);

And guess what the result is?

is [1,2,3,4]?

Console try to see what the result is.


Not surprised.

Actually, the truth ————

That's the number of arguments!

Let's look at one more example

var arr=[' 1 ', ' 4 ', ' 9 ', ' 16 '];

var (function (x) {return parseint (x)});


The result is not normal!

Actually in the call (parseint);

There are three parameters passed to map

Current value (Currentvaluve)//' 1 ', ' 4 ', ' 9 ', ' 16 '

Index of current value (CURRENTINDEX)//0,1,2,3

and the current array (currentarray)//[' 1 ', ' 4 ', ' 9 ', ' 16 '], each time this

Each time the parseint () function is used, only two values (Currentvalue,currentindex) are passed in.

So the result is:

parseint (' 1 ', 0)//1

The second parameter, if passed after the number function is converted to 0 or NaN , is ignored. --mozilla Official documents

parseint (' 4 ', 1)//illegal, NaN

parseint (' 9 ', 2)//illegal, NaN

parseint (' 16 ', 3)//here refers to the note, when parsing the string ' 16 ', found that 6 is greater than or equal to 3, so the subsequent numbers are ignored, leaving only one 1 returned

If parseInt a character is encountered that is not part of the radix cardinality specified by the parameter, then both the character and the character after it are ignored. --mozilla Official documents

When we finally know the truth, we must pay attention to the problem of the number of callback parameters in the map function!

var (function (x) {return parseint (x)});

Questions about callback function parameters in the map method of array

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: 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.