I want to add one to each element of my array. I tried:
myArray=[1,2,3]
myArray.map(a=>a+=1) // tried a++ and a=a+1 too
console.log(myArray) // return [ 1 , 2 , 3 ]
it doesn't worked... so i did that :
myArray=[1,2,3]
mySecondArray=[]
myArray.map(a=>mySecondArray.push(a+1))
console.log(mySecondArray) // return [ 2, 3, 4 ]
So it worked, but I don't anderstand why the first one didn't. Can you explain me why?
Array.mapreturns the mapped array. You can doarr = arr.map(...)if you want to set the array to its mapped version.myArray = myArray.map(a=>a+=1). map returns a new array.myArray.forEach((_, i) => myArray[i] += 1)to mutate the array, but I wouldn't recommend it. Instead replace the current variable with a mapped version of the array, like shown in the answers below.