JavaScript箭头函数map方法中参数num的来源及作用疑问
map() Hey there! Let's unpack your questions about this map() and arrow function code—it's totally normal to scratch your head at first, so no worries.
First, let's recap your code for clarity:
let bigNumbers = [100, 200, 300, 400, 500]; let smallNumbers = bigNumbers.map(num => num / 100);
Your First Question: Where does num come from? Is it a container for new values?
Great question! The num parameter is not a container for the new values you're creating—it's a placeholder that represents each element in the original bigNumbers array as map() loops through it.
Here's what happens step by step:
map()starts with the first element inbigNumbers:100. It passes this value to the arrow function, sonumequals100for this iteration.- The arrow function runs
num / 100(which is100 / 100 = 1), and this result is added to the new array thatmap()is building. - Next,
map()moves to the second element:200. Nownumequals200, the function returns2, and that gets added to the new array. - This repeats for every element in
bigNumbersuntil all elements are processed.
So num is just a variable that holds the current element from the original array during each loop iteration. The new value (like 1, 2, etc.) is what the arrow function returns, and map() collects those returns into the final smallNumbers array.
Your Second Question: Is my understanding of map() returning a new array correct?
Absolutely! That's a spot-on understanding.
map() is designed to create and return a new array where each element is the result of running your arrow function on the corresponding element in the original array. Crucially, it does not modify the original array—your bigNumbers array stays exactly as [100, 200, 300, 400, 500] after running this code. The only change is the new smallNumbers array being created with the transformed values.
Hope this clears things up! Let me know if you want to dive deeper into any part of it.
内容的提问来源于stack exchange,提问作者timSully

