var eg = "one"
var eg2 = "two"
var eg3 = "three"
function randomchoose() {
var rand = ["eg", "eg2", "eg3"];
var act = [eg, eg2, eg3];
choose = rand[Math.floor(Math.random()*rand.length)]
chosen = act[choose]
return [chosen, choose];
}
my issue with this is that I don't know how to make "chosen" be the variable that was randomly chosen.
basically, if it rolls eg, i want chosen to be "one" and same goes for others
------EDIT------ I forgot to specify, i need it to return the variable name as "choose" and the actual value as "chosen"
-
1What exactly do you plan to do with the returned variable name? Sounds like you should create an object instead of use multiple variablescharlietfl– charlietfl2018年05月12日 12:35:45 +00:00Commented May 12, 2018 at 12:35
4 Answers 4
As I understood, you want to return field name and field value, which were randomly chosen. Here's a snippet:
var eg = "one"
var eg2 = "two"
var eg3 = "three"
function choseRandom() {
var rand = ["eg", "eg2", "eg3"];
var act = [eg, eg2, eg3];
var chosenIndex = Math.floor(Math.random()*rand.length);
var fieldName = rand[chosenIndex]
var fieldValue = act[chosenIndex]
return [fieldName, fieldValue];
}
console.log(choseRandom());
console.log(choseRandom());
console.log(choseRandom());
3 Comments
choose and chosen variables, to better reflect the purpose and made them local, instead of global (Why are global variables considered bad practice?). Also you might want to change the return value from array to object, but it really depends on your case I guess.Use an object instead of multiple variables to store the values
var data = {
eg: "one",
eg2: "two",
eg3: "three"
}
function randomchoose() {
var rand = ["eg", "eg2", "eg3"];
choose = rand[Math.floor(Math.random() * rand.length)]
chosen = data[choose]
return [chosen, choose];
}
console.log(randomchoose())
Comments
You just need to store the random number you get and pass with the array when you need it. Here is snippet
Updated as per your question
var eg = "one"
var eg2 = "two"
var eg3 = "three"
function randomchoose() {
var rand = ["eg", "eg2", "eg3"];
var act = [eg, eg2, eg3];
randomNumber = Math.floor(Math.random()*rand.length)
chosen = act[randomNumber]
choose = rand[randomNumber]
return [chosen, choose];
}
console.log(randomchoose())
1 Comment
chosen = act[rand.indexOf(choose)]