Changing an array in a loop in JavaScript
Array elements can be changed in a loop.
To do this, you need to iterate through
the arrays with the usual loop for.
For example, let's multiply
array elements by 2:
javascriptlet arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2;
}
console.log(arr); // shows [2, 4, 6, 8, 10]
Now let's increase each element of the array by one:
javascriptlet arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
arr[i]++;
}
console.log(arr); // shows [2, 3, 4, 5, 6]
And now we increase each element of the array by 5:
javascriptlet arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
arr[i] += 5;
}
console.log(arr); // shows [6, 7, 8, 9, 10]
Задание 1
Given an array of numbers. Loop through this array and square each element of this array.
Задание 2
Given an array of numbers. Loop through this array and subtract one from each element.
Задание 3
Given an array of numbers. Loop through
this array and add 10
to each element.