-4

My current img source is static:

var img = new Image();
img.src = 'http://img.ffffound.com/static-data/assets/6/6f5b12e84fcdb27484c4dfadb19b7c23d16746cd_m.jpg';

How would i go about creating an array of sources and then it being picked randomly?

Creating an array is quite simple, im wondering about the random part and if theres any specifics when creating a source array

Fidycent
  • 3
  • 2

2 Answers2

2

Use Math.random() to generate a random float between 0 and 1, then multiply by the length of your array and use Math.floor() to get a random index into the array:

var a = ['imgs/img1.jpg', 'imgs/img2.jpg', 'imgs/img3.jpg', 'imgs/img4.jpg'];
img.src = a[Math.floor(Math.random() * a.length)];
Ken Bellows
  • 6,711
  • 13
  • 50
  • 78
1

Please next time try to use the internet to search an answer, you'd found this for example, or this.

Anyway in your case:

var srcs = [
   'http://mydomain/myimage1.jpg',
   'http://mydomain/myimage2.jpg',
   ...
];
var src = srcs[Math.floor(Math.random()*srcs.length)];
img.src = src;
Community
  • 1
  • 1
Bolza
  • 1,904
  • 2
  • 17
  • 42