简体   繁体   中英

How to give a variable a random value in javascript

How would I give a variable a random value in javascript?

I can do this:

var myMake = ["Chevy","Subaru","Kia","Honda","Toyota"];

var x = Math.floor(Math.random() * 4 + 1);

var rand = myMake[x];

alert(rand);

which gets the desired effect, giving the variable rand a random value of one of these:

Chevy, Subaru, Kia, Honda, Toyota

but would there be a way to make a function/method that does something like this?:

var rand = randVal("Chevy", "Subaru", "Kia", "Honda", "Toyota");

Thanks!!

function randVal(){
  var x = Math.floor(Math.random() * arguments.length);
  return arguments[x];
}

the arguments is an array like object that refers gives a list of all supplied arguments to a function.

Just to be different!

var x = ["Chevy","Subaru","Kia","Honda","Toyota"].sort(function() {
   return 0.5 - Math.random();
})[0];

alert(x);

jsfiddle

And as a function, but accepting an Array

var randMe = function ( me ) {
    if ( me ) {
        return me.sort(function() {
          return 0.5 - Math.random();
        })[0];
    }
}

alert(randMe(['a','b','c']));

jsfiddle

And some prototyping as well

Array.prototype.rand = function() { 
   return this.sort(function() {
     return 0.5 - Math.random();
   })[0];
}

alert(['a','b','c'].rand());

jsfiddle

Also the actual shuffle function from here .

You can do that very easy with jQuery:

(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
    })(jQuery);

    var items = ["Chevy","Subaru","Kia","Honda","Toyota"];
    var item = $.rand(items);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM