0

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?

6
  • 1
    what does the code have to do with a for loop? Commented Mar 2, 2018 at 23:47
  • Array.push() does the same thing. Commented Mar 2, 2018 at 23:48
  • In the future, I'd recommend doing some searching and making an attempt for yourself before asking others to solve the problem for you. Commented Mar 2, 2018 at 23:49
  • @epascarello Code has printed the all elements of the array! Commented Mar 3, 2018 at 14:29
  • 1
    @kingdaro Yes, your right. I did try but I just didn't post my attempts because I didn't want to create a more confusion! As the newbie to JavaScript, I'm still learning and sometimes what the experienced folks recommend from Stackoverflow I couldn't find anywhere. Big Thank you to all of you guys for your time and help!! Commented Mar 3, 2018 at 14:39

2 Answers 2

2

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help! You help me a lot, Not just with posting the way it could be accomplished but for your time and attempt to help me out with that. I appreciate it.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.