Newbie
Newbie

Reputation: 83

How to use a For Loop to add the elements at the end of the Array in JavaScript

I have an array like so:

const r1 = 1.5;
const r4 = 2.7;
const r5 = 5.8;
const r6 = [r1, r4, r5];
document.write(r6);

And I need to add the following elements at the end of the array r6: 1 2 3 4 5 6 7 8 9 10 .... up to 101 by using For Loop and print this out by using document.write();.

Does anyone know how could I do that?

Upvotes: 0

Views: 143

Answers (2)

Theo
Theo

Reputation: 2042

here, if you want to add 1-101 in existing r6 array

  for (let i = 1; i <= 101; i++) {
    r6.push(i);
  }

Upvotes: 1

acdcjunior
acdcjunior

Reputation: 135762

The method you are looking for is .push(newElement). This method appends values to the end of a given array (in your case r6).

You can use it within a for loop like below.

const r1 = 1.5;
const r4 = 2.7;
const r5 = 5.8;
const r6 = [r1, r4, r5];

// for iterates from 1 to 101
for (var i = 1; i <= 101; i++) {
  r6.push(i); // adds the i element at the end of the r6 array
}

document.write(r6);

Upvotes: 2

Related Questions