简体   繁体   English

在JavaScript / jQuery中随机分配3个数组

[英]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. 然后,我需要在一个div中显示三个数组的结果,其类名称为randomFont。 So each time I use the class randomFont, it will return a random font/size/weight. 因此,每次我使用randomFont类时,它将返回一个随机的字体/大小/粗细。

Any ideas on how I would go about doing this? 关于我将如何执行此操作的任何想法?

Let's say I have 3 variables in each array. 假设我在每个数组中都有3个变量。

  • array 1 (fonts) > font 1, font 2, font 3 数组1(字体)>字体1,字体2,字体3
  • array 2 (font weight) > bold, light, 100 数组2(字体粗细)>粗体,浅色,100
  • array 3 (font-size) > 12px, 24px, 100px 数组3(字体大小)> 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. 然后,我希望一个数组从每个数组中随机选择一个,并在名为randomFont的div>类中显示输出。

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. 确实不需要jQuery,但是应该这样做,因为您没有提供我必须编写的任何示例代码,但这应该可以助您一臂之力。

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/ 您可以在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. 这可能只是对您正在寻找的内容的部分答案,但对我来说,现在还不清楚您总体上的追求是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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