开发者

Announcing the length of an Array

开发者 https://www.devze.com 2023-01-07 12:17 出处:网络
var names=new Array(\"Charlie\",\"Auggie\",\"Hunter\",\"Diesel\",\"Harlum\",\"Tank\",\"Runt\"); var rnames=Math.floor(Math.random(1,names.length));
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.)


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


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消