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

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

from where the arguments coming from?
Impossible to be first argument because 1 can not equal zero.
@epascarello I just tested it and I get all the possible results and no undefined
@user3063875 great, don't forget to accept the answer; this allows someone else to know what the correct answer was.
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.

5 Comments

well it is not a function and it is a waste of time if the OP does not need the whole set.
Yes it works, but it is slow jsperf.com/testrandomvssortarray Written based on how the OP is calling the function. Not passing in an Array.
@epascarello oh, actually you're sliceing that also ... I didn't notice that first ... but thank you anyways!
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 thanks for the explanation and jspref as well ... I guess I should use it more often!
-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);

4 Comments

There is no need for jQuery here to write a function!
I need jQuery for " if ($.isArray(arg)) { "
Kill a fly with a aircraft.
You added more requirements than what the OP wanted and the OP is not passing in an array to the function!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.