javascript - How to push an image into an arra and check if image is in an array -
i trying display random image , once image displayed moved array, if new random image in second array repeat function new image. code 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 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)
change:
if (image in usedimages) to:
if (usedimages.indexof(image) != -1) x in y tests if x 1 of property names of object y, doesn't search values of array.
y.indexof(x) returns position of x in array y. can't use boolean, because returns 0 first element (which falsey), , -1 when element isn't found (which truthy). that's why have compare result -1.
the other problem when retrieve correctanswer.src, contain full url of image, not filename, won't match what's in images. should push filename itself.
function displayrandomimage() { var correctanswer = document.getelementbyid("randomimage"); var image = getrandomimage(); correctanswer.src = image; usedimages.push(image); }
Comments
Post a Comment