Javascript数组随机选择问题

时间:2018-05-12 12:26:14

标签: javascript arrays

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];
}

我的问题是,我不知道如何选择"选择"是随机选择的变量。

基本上,如果它滚动,例如,我想选择"一个"其他人也一样

------ ------ EDIT 我忘了指定,我需要它将变量名称返回为"选择"和实际值"选择"

4 个答案:

答案 0 :(得分:2)

据我所知,您希望返回随机选择的字段名称和字段值。 这是一个片段:



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());




答案 1 :(得分:1)

使用对象而不是多个变量来存储值

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())

答案 2 :(得分:0)

您只需存储您获得的随机数,并在需要时传递数组。这是片段

根据您的问题更新

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())

答案 3 :(得分:0)

selected = act [rand.indexOf(choose)]