JavaScript—我需要从数组返回一个随机字符串,并将索引号存储到一个变量中
我很难做到标题所说的。我可以使用下面的函数从数组返回一个随机字符串。问题是,当我试图将dicePage数组中该字符串的索引存储到变量中时,它会再次调用该函数并随机化该数字。是否有任何方法可以保存数组中随机化字符串的索引,而无需再次随机化?这是我的密码:JavaScript—我需要从数组返回一个随机字符串,并将索引号存储到一个变量中,javascript,Javascript,我很难做到标题所说的。我可以使用下面的函数从数组返回一个随机字符串。问题是,当我试图将dicePage数组中该字符串的索引存储到变量中时,它会再次调用该函数并随机化该数字。是否有任何方法可以保存数组中随机化字符串的索引,而无需再次随机化?这是我的密码: // Array of strings var dicePage = ['r0aidLn', 'tdupQLA', 'jGmaIfG', 'n0SXrxK', 'ZZaPdaZ', 'mAvGJzi']; // Return a random
// Array of strings
var dicePage = ['r0aidLn', 'tdupQLA', 'jGmaIfG', 'n0SXrxK', 'ZZaPdaZ', 'mAvGJzi'];
// Return a random string from the array (this works)
var diceRand = function () {
return dicePage[Math.floor(Math.random() * dicePage.length)];
}
// Save the index of the random string from the array into a variable.
// (This does not work because the function randomizes again and
// returns a mismatched number).
var diceScore = dicePage.indexOf(diceRand());
调用
diceRand
后,您将得到一个对象,该对象可能看起来像{index:0,score:'r0aidLn'}
将函数的值保存在变量中,然后使用indexOf()
var diceString = diceRand();
var diceScore = dicePage.indexOf(diceRand());
但是为什么不让
diceRand()
首先返回索引,因为您显然没有使用它返回的字符串。我使用它返回的字符串来执行其他操作。对不起,我没有解释。但是你的建议很管用谢谢!这是我第一次尝试JavaScript/编码,因此我非常感谢您的帮助:)如果您没有将其分配给变量,您如何将其用于其他用途?
var diceString = diceRand();
var diceScore = dicePage.indexOf(diceRand());