-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);
3
  • You want to pick a URL at random from an array? Commented Aug 29, 2014 at 0:48
  • 3
    You have a very confused understanding of what OR means in programming. It's not how you make a collection of things, it's a boolean or binary operation. Commented Aug 29, 2014 at 0:50
  • @Barmar In fairness, if this was SML, datatype image = url1 | url2 | url3 would be perfectly valid. Commented Aug 29, 2014 at 0:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.