0

Hello everyone I am new here and I am just starting to learn javascript.

I need to come up with a piece off code that alerts a single random element from an array. I have managed to come up with the random element but it alerts all ten of them from the array. While I need t to alert a single one and stop.

This is what I have so far.

    var myList = new Array("gusty", "long", "tremendous", "play", "white", 
    "literate", "baboon", "dusty", "government", "cheer");

    for(i = 0; i < myList.length; i++)
    {
        var y = Math.floor(Math.random() * 10);
        alert(myList[y]);
    }

So when I load this in a browser I get ten random words. But I just want one. I tired putting the var inside the alert but that didn't do anything.

4
  • 1
    Then why did you wrap it in a for loop? Commented Feb 26, 2018 at 11:58
  • When you want only one, you don't really need a loop. Commented Feb 26, 2018 at 11:59
  • alert(myList[Math.floor(Math.random() * 10)]) Commented Feb 26, 2018 at 12:00
  • O my God I feel like and idiot. Thank you so much. You see this is only the first part of the 'task' and the other one requires a loop. Butt once again thank you so much !! Commented Feb 26, 2018 at 12:01

2 Answers 2

2

Just remove the for loop. Since you are referring to the element from array using an index (myList[y]), you don't require a for loop there.

var myList = new Array("gusty", "long", "tremendous", "play", "white",
  "literate", "baboon", "dusty", "government", "cheer");

var y = Math.floor(Math.random() * 10);
alert(myList[y]);

You would generally use a for loop to repeat a certain task. So in your original code, you are generating 10 random numbers, and thus accessing 10 random items from the array. If you need just one, you can simply remove the loop.

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

1 Comment

Thank you very much it worked and i won't make the same mistake.
1

If you want to alert just one, you've no need for a loop. The loop is causing a random value to be selected each time and alerted.

There are some other optimisations you can make.

//we don't normally use new Array() without good reason; use an array literal
//i.e. [1, 2, 3, 'foo'] instead
var myList = ["gusty", "long", "tremendous", "play", "white", 
"literate", "baboon", "dusty", "government", "cheer"];

//remove the loop - and instead of hard-coding 10, let's read the actual length
var y = Math.floor(Math.random() * myList.length);
alert(myList[y]);

Here's a wider discussion on array literals vs. arrays created via the Array() constructor.

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.