0

Sorry if this is a dumb question, I'm a javascript noob

I'm trying to specify a list to find a random entry in. How can I do this without using if/else statements or switches?

var one = ["Japan","Vietnam","Korea"]
var two = ["bleghg","djakd","dasda"]
var three = ["woop","doop","loop"]

function randomItem (list) {
    return list[Math.random()*list.length]
  }
this is a simplification of what I'm trying to do, where I would input the name of an existing list (one, two, or three) and it would get a random item from that list

Thanks in advance for the help!

1
  • Where are you getting the name from? Can't you just directly pass the variable? Commented Jan 6, 2017 at 18:44

3 Answers 3

1

To access a random position in the list, you need to generate a random number against the list length and then round it, like below. No condition testing required.

list[Math.floor(Math.random()*list.length)];

To use this with your code then you would call your function with one of your lists as a parameter. Like so:

console.log(randomItem(one));
Sign up to request clarification or add additional context in comments.

1 Comment

That fixes their code but doesn't answer the question.
0

Replace the list param in the function with the name of the list:

randomItem(one)

var one = ["Japan", "Vietnam", "Korea"]
var two = ["bleghg", "djakd", "dasda"]
var three = ["woop", "doop", "loop"]

function randomItem(list) {
  // you need to round the random number down
  return list[Math.floor(Math.random() * list.length, 10)];
}

var result = randomItem(one);

console.log(result);

Comments

0

Since @Thomas Juranek has corrected your use of Math.random for you, I won't dwell into that. Instead, I will answer your question on retrieving variable using variable names.

I would call this a hack, but variables declared in global are bound to the window object. If you are passing variable name only, you can retrieve it by doing the following:

function getWindowObject(variableName) {
  return window[variableName];
}

It definitely makes more sense to just pass the variable, however. A slightly better way to do this, if you insist on wanting to declare loosely hanging variables outside the function scope, would be to wrap it in an object:

var myPersonalScope = {};
myPersonalScope["one"] = [1, 2, 3];
myPersonalScope["two"] = [4, 5, 6];

function getPersonalScopeObject(variableName) {
  return myPersonalScope[variableName];
}

Comments

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.