Why does a random array throw me undefined?

1

You will see create an array that creates a random text that you put in a link, replacing the spaces by - but throws me undefined.

This is my code:

var array = ["texto 1", "text 2", "text 3", "text 4"];
 var random = Math.floor(Math.random() * array.length);
 $('a').attr('href', array[random].replace(/\s/g, "-"));
    
asked by Eddy Otsutsuki 13.03.2017 в 23:40
source

1 answer

2

The arrays in javascript start from zero and have indexes [0 ... length-1].

You are doing a random that will sometimes point to the [length] index, which does not exist. (Although this possibility is tiny and I am surprised that I am always giving you undefined.

To make sure you never point to index 4, you should:

var array = ["texto 1", "text 2", "text 3", "text 4"];
var random = Math.floor(Math.random() * (array.length-1));
$('a').attr('href', array[random].replace(/\s/g, "-"));

But this is not going to give you an equiprobable result. In that solution, the possibility of the text 4 coming out is tiny.

I would correct it by looking at the edge case (random === array.length) and correcting it to point to the previous index:

var array = ["texto 1", "text 2", "text 3", "text 4"];
var random = Math.floor(Math.random() * array.length);
if(random===array.length) {
   random=(array.length-1)
}
console.log(array[random].replace(/\s/,'-'));

PS: the name "array" is a very bad name for an array.

    
answered by 13.03.2017 в 23:52