我是一个绝对的新手,当涉及到JavaScript和JQuery。我正在尝试开发一个系统,可以从数组中选择一组数字。
我有3个数组和一个系统,将从这些数组中选择一个数字。
var selectedArray = ["sixMatched","fiveMatched","fourMatched","threeMatched"];
var sixMatched = ["367687"];
var fiveMatched = ["567687","337687","167687","367587","368687"];
var fourMatched = ["387087","357187","365627","367620","369627","867987","367610","367604","394687","397681","367247","167683","767697","567617","367207"];
var threeMatched = ["338680","965647","163637","333677","837637","267427","364288","357634","767817","361557","302682","667027","320637","547686","967088","382637","360167","327286","817187","707087","387481","357280","563287","367803","867646","277686","384697","364483","467827","332681"];
我使用math.random函数通过selectedArray数组选择一个随机数组名。
然后我想使用从selectedArray中选择的名称,并使用它从sixMatched,fiveMatched等中选择一个随机值。
$('#play').click(function(){
var winningArray = selectedArray[Math.floor(Math.random()*selectedArray.length)];
var winningNumber = winningArray[Math.floor(Math.random()*winningArray.length)];
$('#number').animateNumber({ number: (winningNumber)});
console.log("Winning array is "+ winningArray +"");
console.log("Winning number is "+ winningNumber +"");
return false;
});
我的代码所做的是从winningArray中选择一个随机字母,而不是将变量的值视为变量选择器。
我希望,由于winningArray将被设置为例如“sixMatched”,代码将选择sixMatched数组并从中选择一个随机值,但实际上它是从winningArray的值中选择一个随机字母。
有人知道我该怎么解决吗?
2条答案
按热度按时间z3yyvxxp1#
不使用单独的顶级变量,而是将数组属性设置为对象:
然后,您可以使用随机选择的字符串值来引用该对象上的属性:
请注意,对
winningArray
的引用被替换为matchedArrays[winningArray]
,因为winningArray
本身是一个字符串值,您可以在JavaScript中使用字符串来索引对象属性。作为一个学术练习,您可以完全摆脱显式的
selectedArray
和dynamically use the list of properties on thematchedArrays
object,因此如果它们发生变化,您不需要手动保持两者同步。x7rlezfr2#
您将从
selectedArray
中获得字符串的随机索引,而不是您要查找的内容。考虑使用一个带有键和值的Object,那么你只需要pick a random key作为'array name'。
因为它是一个对象,所以你可以很容易地将它的键的值作为目标来获取数组,然后从该数组中获取get a random item: