I have an array of images. Each image is clickable and generates a message.The images are in a random array. This all works fine. What I am failing to achieve is the following: When the image is clicked it becomes obsolete so I want to replace the clickable image with a new, unclickable image. I have tried using the array.splice method as follows newArray=myImages.splice(evt.target,1,newImage) This places the new image at position 0 in the new array and not in its original position and no new image is produced to overwrite the older image. I would be grateful for any help.
If we guess that evt
in newArray=myImages.splice(evt.target,1,newImage)
is an Event object, evt.target
is a DOM element , not an index. If this is in the click event you describe, it will be the clicked image.
The first argument of splice
is the index at which to make changes; a number. DOM elements are not numbers.
splice
also returns an array of deleted images, not an updated array. (Unlike methods like map
or slice
, splice
modifies the array you call it on.)
You can find the previous image's index by using indexOf
and then us splice
with that:
const index = myImages.indexOf(evt.target);
if (index !== -1) {
myImages.splice(index, 1, newImage);
}
or you could use map
to create a new array with the new image in place of the clicked one:
newArray = myImages.map(img => img === evt.target ? newImage : img);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.