简体   繁体   中英

Return an array that is randomly filled with string variables

We have three string variables and we want a function to return an array that is randomly filled with those variables.

The desired result should be something like this:

['first string', 'third string', 'second string']; // each variable as a single element

 function generateArray(){ let a = 'first string'; let b = 'second string'; let c = 'third string'; let ourArray = []; // return ourArray randomly filled with 'a' 'b' and 'c' }

First, you need to put all your variables into an array then shuffles (randomly reorders) elements of that array:

  function generateArray(){

        function shuffle(array) {
            return array.sort(() => Math.random() - 0.5);
        }

        let a = 'first string';
        let b = 'second string';
        let c = 'third string';

        var localArray = new Array(a, b, c); 
        return shuffle(localArray);  

    }

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