开发者

How to pick a random number in javascript? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

JavaScript: Getting random value from an array

I have a开发者_运维知识库 list of ten items.

ar = [112,32,56,234,67,23,231,123,12]

How do I choose an item randomly with javascript?


var ar = [112,32,56,234,67,23,231,123,12];
var randomKey = Math.floor(Math.random() * ar.length);
var randomValue = ar[randomKey];

Check out the documentation on the Math object; https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math

You could easily abstract this into a nice function:

function getRandom(array, getVal) {
    var key = Math.floor(Math.random() * array.length);

    if (getVal) {
        return array[key];
    }

    return key;
}

Then you'd call it like getRandom(ar) to get a random key in the array, and getRandom(ar, true) to return a random value in the array.


well something like

var randnum = Math.floor ( Math.random() * ar.length ); 
val random = (ar[randnum]);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜