How do higher-order functions like .map() work inside JavaScript?
P粉107772015
2023-08-25 17:41:30
<p>Nowadays everyone is trying to use these higher order functions to get promising results by writing less code. But I want to know how these functions work internally. </p>
<p>Suppose I wrote something similar</p>
<p>
<pre class="brush:js;toolbar:false;">var numbers = [16, 25, 36];
var results = numbers.map(Math.sqrt);
console.log(results); // [4, 5, 6]</pre>
</p>
<p>I know that each element of the "number" array is iterated one by one, but <em>how</em>? </p>
<p>I tried looking for it but haven't gotten a satisfactory answer yet. </p>
I think every supplier should follow Specifications
A real implementation (e.g. V8) might be a bit more complex, see this answer as a start. You can also refer to the v8 source code in github, but it may not be easy to understand part of it in isolation.
Quote from the above answer:
ES2015 specification:
"length"
)).Let- Pk be ToString(k).
Let - kPresent be HasProperty(O, Pk).
ReturnIfAbrupt(- kPresent).
If - kPresent is true, then
Increase - k by 1.
Let- kValue be Get(O, Pk).
ReturnIfAbrupt(- kValue).
Let - mappedValue be Call(callbackfn, T, «kValue, k >, or".
ReturnIfAbrupt(- mappedValue).
Let - State be CreateDataPropertyOrThrow(A, Pk, mappedValue).
ReturnIfAbrupt(- status).
.map
is just a method that accepts a callback, calls the callback for each item of the array, and assigns the value to the new array. It is nothing special. You can even easily implement it yourself: