0

I am trying to get a user to be prompted with the option to enter a value between 1 and 5, and get access a different array index based on the number they entered.

<h1>JavaScript Arrays</h1>

<p>JavaScript array elements are accessed using numeric indexes (starting from 1).</p>

<h2 id="whichbar"></h2>

<script>
    var chocbars = ["Mars Bar","Chokito","Boost","Crunchie","Picnic"];

    var userchoice = prompt ('Please enter a value between 1 and 5');

    document.getElementById("whichbar").innerHTML = chocbars[4];

</script>

I expect that the user is prompted for a value between 1 and 5, this value then determines which chocolate bar is returned to the screen.

5
  • 1
    use chocbars[userchoice - 1] ? Also, array elements are accessed starting from 0, hence the - 1 Commented Jul 25, 2019 at 9:30
  • You have to add a + before the prompt or else the resultant would be a string type. Commented Jul 25, 2019 at 9:32
  • @KrishnaPrashatt you won't have to since - 1 will convert it to a number for you Commented Jul 25, 2019 at 9:32
  • @Kobe Yeah, with -1, the conversion is taken care Commented Jul 25, 2019 at 9:34
  • Thank you all very much, this was helpful. Much appreciated.I apologise for the unnecessary lines at the beginning of my explanation. Commented Jul 25, 2019 at 9:36

1 Answer 1

3

You could take the index of the array by getting a zero based value, hence indices start with zero.

document.getElementById("whichbar").innerHTML = chocbars[userchoice - 1];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much this is helpful, also i apologise for the unnecessary line at the beginning.

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.