I'm quite new at this.... its to create a quote from three sections of the phrase: start. middle and end... and randomly select one from each.
The code works but I didn't want to repeat the code underneath with the Math.floor/Math.Random three times.
Any ideas on how to not repeat the code?
Thanks!
var quotes = {
start: ["start1 ", "start2 ", "start3 "],
middle: ["middle1 ", "middle2 ", "middle3 "],
end: ["end1 ", "end2 ", "end3 "],
};
var quoteRandom = "";
for (var y in quotes) {
console.log(quotes[y]);
}
quoteRandom += quotes.start[Math.floor(Math.random() * 3)];
quoteRandom += " " + quotes.middle[Math.floor(Math.random() * 3)];
quoteRandom += " " + quotes.end[Math.floor(Math.random() * 3)];
console.log(quoteRandom);
You could take the power of a function and a callback, which is basically a function for another function which calls the function for each of item of an array, for example.
Methods used:
Object.values
for getting all values of an object
Array#map
for returning a value for each item (in this case take the array and return a random item)
and a function for getting a random value out of an array.
function getRandomValue(array) { return array[Math.floor(Math.random() * array.length)]; } var quotes = { start: ["start1 ", "start2 ", "start3 "], middle: ["middle1 ", "middle2 ", "middle3 "], end: ["end1 ", "end2 ", "end3 "], }, quoteRandom = Object.values(quotes).map(getRandomValue).join(' '); console.log(quoteRandom);
Just wrap Math.floor(Math.random() * 3) as return value of function and reuse same function where ever required to avoid duplicate lines of code
var quotes = { start: ["start1 ", "start2 ", "start3 "], middle: ["middle1 ", "middle2 ", "middle3 "], end: ["end1 ", "end2 ", "end3 "], }; var quoteRandom = ""; for (var y in quotes) { console.log(quotes[y]); } function test(){ return Math.floor(Math.random() * 3) } quoteRandom += quotes.start[test()]; quoteRandom += " " + quotes.middle[test()]; quoteRandom += " " + quotes.end[test()]; console.log(quoteRandom);
code sample - https://codepen.io/nagasai/pen/zWGwPg?editors=1111
use array.reduce()
. This way you don't have to worry about start
, middle
and end
length
var quotes = { start: ["start1 ", "start2 ", "start3 "], middle: ["middle1 ", "middle2 ", "middle3 "], end: ["end1 ", "end2 ", "end3 ","end4 ", "end5 ", "end6"], }; var quoteRandom = [quotes.start,quotes.middle,quotes.end].reduce((str,el)=> {return str+=el[Math.floor(Math.random() * el.length)]},""); console.log(quoteRandom);
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.