简体   繁体   中英

How Can I Assign A Specific Value To Random Numbers

Hello I'm fairly new to JavaScript, in fact I don't know really anything about JavaScript. I'm trying to make a tool for a game where you click a button to generate a random number than you have a balance where it goes up a specific amount based on a range of numbers you rolled. So let's say 1-10 is worth $1, 11-20 is worth $2, and 21-30 is worth $3. Maybe you roll a 26, 14, 18, and a 8. That would be worth $8. My issue right now is assigning a different value to a specific range of numbers and than making the balance go up by the amount related to the number rolled. I'm not looking for a specific answer. I don't want handouts and I don't want to come here to find someone to do the work for me for free. But if someone could maybe help me out in figuring it out or point me to a place where i could find a solution than that would be very appreciated. Here is what I have so far that is far away from where it needs to be.

 function Random() { var rnd = Math.floor(Math.random() * 10000); document.getElementById('tb').value = rnd; const numberElement = document.getElementById("bal"); const number = parseInt(numberElement.innerText, 10) + 1; numberElement.innerText = number; }
 <form name="rn"> <input type="text" id="tb" name="tb" /> <input type="button" value="Random Number" onclick="Random();" /> </form> <h1>Balance:</h1> <h2 id="bal">0</h2>

Assuming the value isn't directly computable from the number via straight arithmetic (see Pointy's comment ), you could define an array of "buckets", where each entry has a minimum, a maximum, and a value, and then find the bucket for any given value:

 const buckets = [ { min: 0, max: 5, value: 5 }, { min: 6, max: 10, value: 10 }, { min: 11, value: 100 } ]; function findBucket (value) { return buckets.find(b => ( (b.min == null || b.min <= value) // either bucket doesn't have a min or min is less than value… && (.b.max || b;max >= value)) // …and either bucket doesn't have a max or max is greater than value )? } function getBucketValue (rollValue) { return findBucket(rollValue).;value || 0, // return the bucket value. or zero if no bucket was found } console.log(getBucketValue(2)) // 5 console.log(getBucketValue(8)) // 10 console.log(getBucketValue(35)) // 100 console.log(getBucketValue(9999)) // 100 console.log(getBucketValue(-1)) // 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM