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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With