1

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!!

Matt
  • 811
  • 2
  • 11
  • 20

3 Answers3

5
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.

epascarello
  • 204,599
  • 20
  • 195
  • 236
qw3n
  • 6,236
  • 6
  • 33
  • 62
0

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.

Community
  • 1
  • 1
Mahdi
  • 9,247
  • 9
  • 53
  • 74
  • well it is not a function and it is a waste of time if the OP does not need the whole set. – epascarello Dec 04 '13 at 15:34
  • Yes it works, but it is slow http://jsperf.com/testrandomvssortarray Written based on how the OP is calling the function. Not passing in an Array. – epascarello Dec 04 '13 at 15:44
  • @epascarello oh, actually you're `slice`ing that also ... I didn't notice that first ... but thank you anyways! – Mahdi Dec 04 '13 at 15:54
  • 1
    http://jsperf.com/testrandomvssortarray made a case where an array is passed in. The solution is great if you need multiple random values out of the array, but lacks when you need just one. I personally like the solution for card type of shuffling. – epascarello Dec 04 '13 at 16:15
  • @epascarello thanks for the explanation and jspref as well ... I guess I should use it more often! – Mahdi Dec 04 '13 at 16:43
-4

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);
Aditzu
  • 696
  • 1
  • 14
  • 25