简体   繁体   中英

Add 1 to each element using .map

I have an array created and I would like to know how to use the.map function to add 1 to each element of the array

 function range(n){ let arr= [...Array(n).keys()]; }

JS arrays are zero index based, so keys will return values starting from zero, you need to manually add the 1 so either add .map(i=> i+1) after arr, or you can simply use Array.from instead,

 function range(n) { let arr = Array.from({ length: n }, (_, i) => i + 1) return arr } console.log(range(9))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM