最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do you select a random variable within a function in JavaScript? - Stack Overflow

programmeradmin4浏览0评论

I have put multiples variables within a function and I was wondering if there was any way possible in JavaScript to select a variable within that function at random. Any help is greatly appreciated. Thank you so much.

I have put multiples variables within a function and I was wondering if there was any way possible in JavaScript to select a variable within that function at random. Any help is greatly appreciated. Thank you so much.

Share Improve this question asked Jan 20, 2013 at 6:21 Eddie VartanessianEddie Vartanessian 651 gold badge1 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

If you use an array instead of multiple variables then you can select a random element from the array:

function test() {
    var values = ["test","values","go","here"],
        valueToUse = values[Math.floor(Math.random() * values.length)];
    // do something with the selected value
    alert(valueToUse);
}

Demo: http://jsfiddle/XDn2f/

(Of course the array doesn't have to contain simple values like the strings I showed, you could have an array of objects, or references to other functions, etc.)

If one of your parameters is an array you can randomly select one value from it.

function myFunc(arrayInput)
{
     var randomIndex = Math.floor((Math.random()*10)+1);
     return (arrayInput[randomIndex]);
}

If you have N variables, then it is cleanest to put them in an array and generate a random index into that array.

var items = [1,2,3,4];
var index = Math.floor(Math.random() * items.length);
items[index] = whatever;

If you only have a couple variables, you can generate a random number and use an if/else statement to operate on the desired variable.

var a, b;
var index = Math.random();
if (index < 0.5) {
    // operate on a
    a = 3;
} else {
    // operate on b
    b = 3;
}
发布评论

评论列表(0)

  1. 暂无评论