what's .map() doing?
I found an interesting question on StackOverflow, saying:
Using console in Chrome, input is
1 | [0].map(Array); |
and output is
1 | [0, 0, [0]]; |
It looks confused at first, and by looking up the reference on MDN, I found
var new_array = arr.map(function callback(currentValue, index, array) {
}[, thisArg])
and that’s easily explained.
We pass currentValue = 0, index = 0, array=[0]
into Array: we got
1 | Array(0, 0, [0]); |
Wait, how about multiple values?
1 | [0, 0].map(Array); |
we got
1 | [ |
We pass currentValue = 0, index = 0, array=[0]
into Array, and then, we pass currentValue = 0, index = 1, array=[0]
into Array. And map returns an array.
no problem!
How about Number
?
1 | [0].map(Number); |
should that return a
1 | [0, 0, 0]; |
No way. And why?
should it pass currentValue = 0, index = 0, array=[0]
into Number?
It should, but Number only takes one argument, the first one. It equals that we pass 0
into Number:
1 | Number(0); |
It seems that we solved full questions. But that’s not the end.
parseInt
shows different result
trying:
1 | [0, 0].map(parseInt); |
You must think we got [0, 0]
Some clever boy looks up reference on MDN:
parseInt(string, radix);
it equals parseInt([0, 0])
Oh, we must got [0]
instead.
Well, how about ?
1 | [10, 10].map(parseInt); |
emmmm, We will got [10]
, because 10
in 10-radis
is 10
Holy wrong!
Remember, we pass currentValue, index, array
for each value?index
is important!
The answer is left for you.
What do you get from this passage?