简体   繁体   中英

Random value from multidimensional array

Via javascript, I am trying to display a random value from an array after cycling through select objects within the array. I have this working except I only want the first part of the array to show not both values. I have it working perfectly showing both values but I can't get it to just show the first item in the random array selected (Ex: Op1 not Op1Opt1b). Here is my code:

 $(document).ready(function(){ var i, word, rnd, words, fadeSpeed, timer; words = [ ['Opt1','Opt1b'], ['Opt2','Opt2b'], ['Opt3','Opt3b'], ['Opt4','Opt4b'], ['Opt5','Opt5b'], ['Opt6','Opt6b'], ['Opt7','Opt7b'], ['Opt8','Opt8b'], ['Opt9','Opt9b'], ['Opt10','Opt10b'], ['Opt11','Opt11b'], ['Opt12','Opt12b'], ['Opt13','Opt13b'], ['Opt14','Opt14b'], ['Opt15','Opt15b'], ['Opt16','Opt16b'], ['Opt17','Opt17b'], ['Opt18','Opt18b'], ['Opt19','Opt19b'], ['Opt20','Opt20b'] ]; timer = 100; for(i = 0; i < 8; i ++) { if(i===8) { word= words[rnd]; } else { rnd= Math.floor(Math.random() * words.length); word= words[rnd]; words.splice(rnd, 1); } (function(word) { $('h1').fadeOut(fadeSpeed, function() { $(this).html(word); }).fadeOut('fast').delay(timer).fadeIn('fast'); })(word); } });
 body { margin: 0; padding: 0; } h1 { text-transform: uppercase; margin: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1></h1>

You just need to change the html you are showing

$('h1').fadeOut(fadeSpeed, function() {
    $(this).html(word[0]);
})

 $(document).ready(function(){ var i, word, rnd, words, fadeSpeed, timer; words = [ ['Opt1','Opt1b'], ['Opt2','Opt2b'], ['Opt3','Opt3b'], ['Opt4','Opt4b'], ['Opt5','Opt5b'], ['Opt6','Opt6b'], ['Opt7','Opt7b'], ['Opt8','Opt8b'], ['Opt9','Opt9b'], ['Opt10','Opt10b'], ['Opt11','Opt11b'], ['Opt12','Opt12b'], ['Opt13','Opt13b'], ['Opt14','Opt14b'], ['Opt15','Opt15b'], ['Opt16','Opt16b'], ['Opt17','Opt17b'], ['Opt18','Opt18b'], ['Opt19','Opt19b'], ['Opt20','Opt20b'] ]; timer = 100; for(i = 0; i < 8; i ++) { if(i===8) { word= words[rnd]; } else { rnd= Math.floor(Math.random() * words.length); word= words[rnd]; words.splice(rnd, 1); } (function(word) { $('h1').fadeOut(fadeSpeed, function() { $(this).html(word[0]); }).fadeOut('fast').delay(timer).fadeIn('fast'); })(word); } });
 body { margin: 0; padding: 0; } h1 { text-transform: uppercase; margin: 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1></h1>

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