Home > Net >  Removing [object PointerEvent] from my JavaScript variable when used in a source
Removing [object PointerEvent] from my JavaScript variable when used in a source

Time:08-05

So basically in the bellow code I want to access the image which is related to the index of the array. Now on the console.log(i), I get "1" as there are two elements in the array.

However, when I click the "array" I get "../[object PointerEvent]1.png". This causes an error as the file name is 1.png not the above.

Does anyone know how I can remove the [object PointerEvent] so I just have the "../1.png"?

Thank you

for(let i = 0; i < array.length; i  ) {
    console.log(i);
    array[i].addEventListener("click", function nextImage(i) {
        image.src = i  ".png";
    });
}

CodePudding user response:

The value passed into the object will automatically be the event and not the value from the array. A better way of doing this is:

array[i].addEventListener("click", function nextImage(a){return (event)=>{
        image.src = a  ".png"}
        }(i)
    );

CodePudding user response:

You have two different variables named i.

  • The one defined in the for loop that you want
  • The parameter if your callback function which is passed the Event object that you get

Rename the second one so you stop shadowing the first one. Traditional name are e or event but since you aren't using it, you could just remove it.

Using a tool like eslint with the no-shadow rule could have caught this error for you.

  • Related