Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

javascript - Randomizing elements in an array?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
};

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...