Reputation: 87
Looking for a resource to explain why when I run the below code, my original array doesn't change.
arr = [1,2,3,4];
for(let val of arr){
val = val * 2;
console.log(val);
}
console.log(arr);
I am learning about for...in and for...of loops and not sure why my console.log(arr) doesn't print out [2,4,6,8].
Upvotes: 5
Views: 5989
Reputation: 488
Yes, you can use for of
with entries
arr = [1,2,3,4];
for (let [i, val] of arr.entries()){
arr[i] = val = val * 2;
console.log(val);
}
console.log(arr);
Upvotes: 0
Reputation: 1752
You can achieve this using forEach
too, which runs a particular function for every value in the array.
arr = [1,2,3,4];
arr.forEach((d, i, arr) => arr[i]*=2);
console.log(arr);
Upvotes: 1
Reputation: 121998
You are modifying and not inserting in back.
Better you use for each
this case. So that you'll be able to modify the array. Using of
make things complicated.
arr = [1,2,3,4];
arr.forEach(function(part, index, array) {
array[index] = array[index]*2;
});
console.log(arr);
Upvotes: 2
Reputation: 4830
The problem here is that the the identifier val
is being overwritten. With another integer and val is just a temp variable invoked each iteration of the loop. If you used an object, and did not reassign the variable, your values would remain intact
// Object values
var x = [{z:1},{z:2}]
for(let y of x){
// No reassignment
y.z=3;
}
console.log(x); //[{"z":3},{"z":3}]
If you want to modify an array of simple types in place, you can do something like:
var q = [5,6,7];
for( i in q){
q[i] = q[i] * 2;
}
console.log(q); //[10, 12, 14]
Upvotes: 2
Reputation: 520968
Use a for loop, which enables you to make the assignments "stick" in the original array.
arr = [1,2,3,4];
for (var i=0; i < arr.length; i++) {
arr[i] = 2*arr[i];
console.log(arr[i]);
}
The issue with what you were originally doing is that val
is just a variable with no real connection to the underlying array. Hence, doubling val
has no effect on the array itself.
Upvotes: 2