Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a JavaScript array in place?

How do I change a JS array in place (like a Ruby "dangerous" method, e.g. with trailing !)

Example:

If I have this:

var arr = [1, 2, 3]

How can I make this:

arr === [2, 4, 6]

(assuming I have an appropriate function for doubling numbers) in one step, without making any more variables?

like image 485
Choylton B. Higginbottom Avatar asked Oct 20 '25 05:10

Choylton B. Higginbottom


1 Answers

Use Array.prototype.forEach() , third parameter is this : input array

var arr = [1, 2, 3];
arr.forEach(function(el, index, array) {
  array[index] = el * 2
});
console.log(arr)
like image 189
guest271314 Avatar answered Oct 21 '25 19:10

guest271314