简体   繁体   中英

Randomizing 3 arrays in JavaScript/jQuery

I would like to randomize three arrays for fonts, font size, font weight. I then need to display the results of the three arrays in a div, with a class name of randomFont. So each time I use the class randomFont, it will return a random font/size/weight.

Any ideas on how I would go about doing this?

Let's say I have 3 variables in each array.

  • array 1 (fonts) > font 1, font 2, font 3
  • array 2 (font weight) > bold, light, 100
  • array 3 (font-size) > 12px, 24px, 100px

Then I want an an array to randomly choose one from each and display the output in a div>class called randomFont.

How would I do this?

Don't really need jQuery but this should do it, since you didn't supply any example code I've had to make it up but this should get you on your way.

var item = items[Math.floor(Math.random() * items.length)];

do this for each array.

You can see one approach at http://jsfiddle.net/CrossEye/bwsvy/

var fonts = ['Arial', 'Helvetica', 'Georgia', 'Tahoma', 'Verdana'];
var weights = ['normal', 'bold', 'lighter'];
var sizes = ['16px', '20px', '24px', '36px', '40px'];

var choose = function(arr) {
    return arr[Math.floor(Math.random() * arr.length)];
};

// ...
var text = choose(sizes) + ' ' + choose(weights) + ' '  +  choose(fonts);
output.innerHTML = '<div class="randomFont">' + text + '</div>';
// e.g. '24px bold Tahoma'

It's not clear what you mean by randomizing the arrays. If you have a fixed list of values and you want to rearrange them in place, then you want a shuffle functions, something like this:

var shuffle = function(arr) {
    for (var i = arr.length; i--;) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

That might be a partial answer to what you're looking for, but it's really not clear to me what you're after overall.

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