Norbert
Norbert

Reputation: 2771

JavaScript: Array is undefined

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?

Upvotes: 1

Views: 1402

Answers (5)

Emmerman
Emmerman

Reputation: 2343

var i = Math.floor(Math.random()*name.length);

Upvotes: 0

Kevin
Kevin

Reputation: 5694

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]);

Array documentation reference

Upvotes: 4

Luke
Luke

Reputation: 1511

Is it possible there are less than 201 lines of text in nameList.txt?

Upvotes: 0

Rob_IGS
Rob_IGS

Reputation: 575

Did you try

var i = parseInt(random());

?

Upvotes: -1

Pranay Rana
Pranay Rana

Reputation: 176896

Thsi 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 
}

Upvotes: 1

Related Questions