-2

Trying to add randomness to which image is displayed. Issue with saying calling and or statement.

var image = url3 | url2 | url1;
    buildImage(image);



function buildImage(imagesrc) {
    var img = document.createElement('img');
    img.src = imagesrc;
    document.getElementById('content').appendChild(img);
James121
  • 45
  • 8

2 Answers2

2
var images = [url3, url2, url1];
var image = images[(Math.random() * images.length)|0];

The "or" operators are not probabilistic "or" that will return one value or another. They are very specific: || will return the first value unless it's falsy, in which case it returns the second; and | converts both arguments to integers and applies the same operation to each individual binary digit.

Amadan
  • 191,408
  • 23
  • 240
  • 301
1

Instead of using separate variables, make a urls array:

var urls = [
    "http://example.com/img1.jpg",
    "http://example.com/img2.jpg",
    "http://example.com/img3.jpg"
];

You can then select a random URL by doing:

var url = urls[Math.floor(Math.random() * urls.length)];

And call buildImage:

buildImage(url);
Overv
  • 8,433
  • 2
  • 40
  • 70