Kamila Jarek
Kamila Jarek

Reputation: 117

How to alert a single element from an array in javascript?

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.

Upvotes: 0

Views: 1115

Answers (2)

Mitya
Mitya

Reputation: 34576

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.

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14551

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.

Upvotes: 2

Related Questions