Home > OS >  How to manipulate numbers in array with for loop in JS
How to manipulate numbers in array with for loop in JS

Time:06-10

I have a array:

let numbers = [5, 10, 15, 25, 30];

I want to increment them all by one using a for loop. The result should be 6, 11, 16, 26 and 31.

But I can do this:

let numbers = [5, 10, 15, 25, 30];

for (let i = 0; i < numbers.length; i  )
  console.log(numbers   1);

CodePudding user response:

let numbers = [5, 10, 15, 25, 30]; 

for (let i = 0; i < numbers.length; i  ) {
  numbers[i]  
}

CodePudding user response:

Use this loop:

for (let i = 0; i < numbers.length; i  ){
    numbers[i]  = 1
}
console.log(numbers)

Output: [6, 11, 16, 26, 31]

CodePudding user response:

const numbers = [5, 10, 15, 25, 30];

const result = numbers.map(num => num   1);
console.log(result); //[6, 11, 16, 26, 31]
  • Related