Mooney_S Mooney_S - 27 days ago 4
Javascript Question

How to push an image into an arra and check if image is in an array

I am trying to display a random image and once this image is displayed it is moved to another array, if the new random image is in the second array then it will repeat the function to get a new image. My code is as follows

var correctAnswer
var image
var images = new Array(10)
images[0] = "Bridleway.png"
images[1] = "Bus.png"
images[2] = "Footpath.png"
images[3] = "House.png"
images[4] = "Park.png"
images[5] = "Pillar.png"
images[6] = "Road.png"
images[7] = "Train.png"
images[8] = "Worship.png"
images[9] = "Youth.png"
//selecting a random image
var usedImages = new Array()
function getRandomImage() {
image = images[Math.floor(Math.random() * 10)];
if (image in usedImages)
getRandomImage();
else
return image;
}

function displayRandomImage() {
correctAnswer = document.getElementById("randomImage");
correctAnswer.src = getRandomImage();
usedImages.push(correctAnswer.src)

Answer

Change:

if (image in usedImages)

to:

if (usedImages.indexOf(image) != -1)

x in y tests if x is one of the property names of the object y, it doesn't search the values of an array.

y.indexOf(x) returns the position of x in the array y. You can't use it as a boolean, because it returns 0 for the first element (which is falsey), and -1 when the element isn't found (which is truthy). That's why you have to compare the result with -1.

The other problem is that when you retrieve correctAnswer.src, it will contain the full URL of the image, not just the filename, so it won't match what's in images. You should push the filename by itself.

function displayRandomImage() {
    var correctAnswer = document.getElementById("randomImage");
    var image = getRandomImage();
    correctAnswer.src = image;
    usedImages.push(image);
}