I have a multi-line variable and want to select a random line:
$.get('namelist.txt', function(nameList) {
name = nameList.split('\n');
var i = random();
alert(name[i]); // this is undefined
});
The random() function returns a random number:
function random() {
return Math.floor(Math.random()*201);
}
The problem is that the alert says undefined. If I replace line 3 with var i = 5, it works. I tested i with typeof and they're numbers in both cases. Any ideas on how to fix this?
5 Answers 5
You should generate a random number depending on the length of the array. 201 is probably exceeding the highest index of your array.
You could adjust your random function to accept a length instead:
function random(len) {
return Math.floor(Math.random() * len);
}
And then use it like this:
var name = nameList.split('\n');
var i = random(name.length);
alert(name[i]);
8 Comments
-1 from here :)-1 as a resultThsi is because the name is an array
which may contains around let say 3 element in it
if the random function have value more than 3 it will give you an error as you have right now.
on suggestion
first change no element in the array and the number generated by the random function.
if (name.length< randomnumber)
{
//do logic what you want
}
Comments
Is it possible there are less than 201 lines of text in nameList.txt?
Comments
var i = Math.floor(Math.random()*name.length);
Comments
Did you try
var i = parseInt(random());
?
1 Comment
Math.floor doesn't return a string.
namehave less than 200 elements?varin front ofnamein your function. Without it, unless you havenamedefined in the scope enclosing the code you've quoted, you're overwriting thewindow.nameproperty (which is almost certainly not what you want). In general, be sure to declare your variables so as not to fall prey to The Horror of Implicit Globals.