随机化数组中的元素? [英] Randomizing elements in an array?

查看:35
本文介绍了随机化数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的一位艺术家朋友创建了一个网站,她希望布局保持不变,但她还希望将她制作的新画作混合到当前布局中.所以我在主图库页面上有 12 个缩略图(thumb1 - thumb12)和 18 个图像(img1 - img18)要放置

I've created a site for an artist friend of mine, and she wants the layout to stay the same, but she also wants new paintings she'd produced to be mixed into the current layout. So I have 12 thumbnails (thumb1 - thumb12) on the main gallery page and 18 images (img1 - img18) to place as well

我想到的方法是创建一个包含所有图像的数组,将其随机化,然后简单地刮掉前 12 个并将它们加载到拇指槽中.另一种方法是从数组中随机选择 12 张图像.在第一种情况下,我找不到随机化数组元素的方法.在后一种情况下,除了使用第二个数组,这似乎非常低效和可怕.

The approach I thought of was to create an array of all the images, randomize it, then simply scrape off the first 12 and load them into the thumb slots. Another approach would be to select 12 images randomly from the array. In the first case, I can't find a way to randomize the elements of an array. In the latter case, I can't wrap my brain around how to keep images from loading more than once, other than using a second array, which seems very inefficient and scary.

顺便说一下,我正在用 Javascript 完成所有这些工作.

I'm doing all of this in Javascript, by the way.

推荐答案

我不久前写了这个,它恰好适合您正在寻找的内容.我相信 ojblass 指的是 Fisher-Yates shuffle:

I wrote this a while ago and it so happens to fit what you're looking for. I believe it's the Fisher-Yates shuffle that ojblass refers to:

Array.prototype.shuffle = function() {
   var i = this.length;
   while (--i) {
      var j = Math.floor(Math.random() * (i + 1))
      var temp = this[i];
      this[i] = this[j];
      this[j] = temp;
   }

   return this; // for convenience, in case we want a reference to the array
};

请注意,修改 Array.prototype 可能被认为是错误的形式.您可能希望将其实现为将数组作为参数的独立方法.无论如何,完成它:

Note that modifying Array.prototype may be considered bad form. You might want to implement this as a standalone method that takes the array as an argument. Anyway, to finish it off:

var randomSubset = originalArray.shuffle().slice(0,13);

或者,如果您不想实际修改原始文件:

Or, if you don't want to actually modify the original:

var randomSubset = originalArray.slice(0).shuffle().slice(0,13);

这篇关于随机化数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆