随机化数组中的元素?
我为我的一位艺术家朋友创建了一个网站,她希望布局保持不变,但她也希望将她制作的新画混合到当前布局中。 因此,我在图库主页面上有 12 个缩略图(thumb1-thumb12),还有 18 个图像(img1-img18)要放置。
我想到的方法是创建所有图像的数组,将其随机化,然后简单地刮掉首先 12 个并将它们装入拇指槽中。 另一种方法是从阵列中随机选择 12 个图像。 在第一种情况下,我找不到随机化数组元素的方法。 在后一种情况下,除了使用第二个数组之外,我无法思考如何防止图像多次加载,这看起来非常低效且可怕。
顺便说一句,我是用 Javascript 完成所有这些工作的。
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
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.
I'm doing all of this in Javascript, by the way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不久前写过这篇文章,它恰好符合您正在寻找的内容。 我相信 ojblass 指的是 Fisher-Yates shuffle:
请注意,修改 Array.prototype 可能被认为是不好的形式。 您可能希望将其实现为将数组作为参数的独立方法。 无论如何,要完成它:
或者,如果您不想实际修改原始内容:
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:
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:
Or, if you don't want to actually modify the original:
您应该实施 Fisher-Yates shuffle(也称为 Knuth shuffle)。
看看提供的很好的答案
You should implement the Fisher-Yates shuffle (otherwise known as the Knuth shuffle).
Look at the great answer provided here.
你的第一种方法会起作用。 只需将 18 个元素打乱并取出前 12 个即可。
Your first approach would work. Just shuffle the 18 elements and take the first 12.
我最近自己也遇到了这个问题。 这里的帖子有帮助:http://waseemsakka.com/2012/02/14/javascript-dropping-the-last-parts-of-an-array-and-randomizing-the-order-of -an-array/ 。
基本上,从随机化数组开始:
这将随机化 18 个元素的顺序。 然后,如果只保留前 12 个元素,则只需删除最后 6 个元素即可:
I recently came across this problem myself. The post here helped: http://waseemsakka.com/2012/02/14/javascript-dropping-the-last-parts-of-an-array-and-randomizing-the-order-of-an-array/ .
Basically, start by randomizing your array:
This will randomize the order of your 18 elements. Then to only keep the first 12 elements, you would just drop the last 6: