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?
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.