0

Is there a way to combine a loop with an array? And to add a specific value to all elements of an array?

Like If I have Var y = [1,2,3,4,5] And Var x =10 If I want to use a loop to increase all elements of array y with var x how do I do it

3rd Aug 2021, 2:17 PM
David
David - avatar
3 ответов
+ 4
The Sololearn JavaScript lesson on arrays teaches that array elements are accessed by their index number (y[0], y[1], y[2],...). And the lesson on loops teaches that for() loops have an index variable that determines how many times to execute the loop. What it fails to teach is that you can use a variable for the array index. That means you can use the for() loop index variable also as the array index. So instead of x = 10 y[0] += x y[1] += x y[2] += x y[3] += x y[4] += x You can shorten the code to this: x = 10 for (i=0; i<5; i++) { y[i] += x; }
3rd Aug 2021, 2:36 PM
Brian
Brian - avatar
+ 3
While you can use a for loop or a forEach loop, you can also use a map. Like this: var y = [1,2,3,4,5]; var x = 10; y = y.map((num)=>{return num+x});
3rd Aug 2021, 2:36 PM
Baribor Saturday
Baribor Saturday - avatar
+ 1
Thanks a lot
3rd Aug 2021, 2:52 PM
David
David - avatar