I’m an absolute novice when it comes to Javascript and Jquery. I’m trying to develop a system that will select a set number from an array.
I’ve got 3 arrays and a system that will select one of the numbers from these arrays.
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"];
I’m using the math.random function to select a random array name via the selectedArray array.
I want to then use the name picked from selectedArray and use that to select a random value from either sixMatched, fiveMatched, etc.
$('#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;
});
What my code is doing though is selecting a random letter from winningArray rather than treating the value of the variable as a variable selector to then.
I was hoping that since winningArray would be set to for example "sixMatched" the code would select the sixMatched array and select a random value from it, but instead it’s selecting a random letter from the value of winningArray instead.
Does anyone know how I can fix this?
2
Answers
Instead of separate top-level variables, make the arrays properties on an object:
Then you can use your randomly selected string value to reference the property on that object:
Notice that the reference to
winningArray
was replaced withmatchedArrays[winningArray]
, sincewinningArray
itself is a string value and you can use strings to index object properties in JavaScript.As an academic exercise at this point, you can get rid of the explicit
selectedArray
entirely and dynamically use the list of properties on thematchedArrays
object, so you don’t need to manually keep the two synchronized if they ever change.You are getting a random index of the string from
selectedArray
, not what you’re looking for.Consider using an Object with keys and values, then you just need to pick a random key for the ‘array name’.
Since it’s an object, you can easily target it’s key’s value to get the array, then get a random item from that array: