views:

56

answers:

3
var names=new Array("Charlie","Auggie","Hunter","Diesel","Harlum","Tank","Runt");
    var rnames=Math.floor(Math.random(1,names.length));

That is my code, rnames is always 0. How would I tell the length of a table? (the length is 7 - in other words, i want to tell how many entries are inside of a table.)

+5  A: 

In Javascript, Math.random() doesn't take any parameters.
Any parameters you pass it are silently ignored, and it always returns a real number between 0 and 1.

Instead, you should multiply the number by the length of the array, like this:

var names = ["Charlie","Auggie","Hunter","Diesel","Harlum","Tank","Runt"];
var randomIndex = Math.floor(Math.random() * names.length);
SLaks
In addition, Math.random()'s return value will always be between 0 and 1.
rchern
Anonymous the Great
And, rchern, he said that in line 2 of his answer.
Anonymous the Great
Since I cannot create another question for another 20 minutes, how do I do this? (I have 98 rep)How do I create a line break in JavaScript? This is what I tried, but it did not work..`box.value=rnames+"/n"+names[rnames];`
Anonymous the Great
Change it to `"\n"`.
SLaks
Given the way the site works, he could have added it after rchern posted the comment, and it wouldn't show up as an edit since it was within 5 minutes of being posted.
GalacticCowboy
+1  A: 
var names=new Array("Charlie","Auggie","Hunter","Diesel","Harlum","Tank","Runt");
var rnames=Math.floor(Math.random()*names.length)
volkan er
+1  A: 

I don't think Math.random() takes any parameters. If you want an integer between two integres(min & max) try this

Math.floor(Math.random() * (max - min + 1)) + min;

Regards, Satyajit

Satyajit