Choylton B. Higginbottom
Choylton B. Higginbottom

Reputation: 2304

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?

Upvotes: 3

Views: 5462

Answers (1)

guest271314
guest271314

Reputation: 1

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)

Upvotes: 5

Related Questions