admin管理员组

文章数量:1417576

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?

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?

Share Improve this question edited Feb 10, 2023 at 0:20 Cadoiz 1,6762 gold badges25 silver badges35 bronze badges asked Jan 5, 2016 at 18:46 Choylton B. HigginbottomChoylton B. Higginbottom 2,3243 gold badges24 silver badges36 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

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)

本文标签: How do I change a JavaScript array in placeStack Overflow