pokemonContainer.addEventListener('click', function (e) {
let favourite = getStorageItem('pokemon');
let eTargetID = e.target.dataset.id;
let found = favourite.some((el) => el.id === eTargetID);
console.log(found);
console.log(eTargetID);
if (!found) {
favourite.push(pokemonArray[e.target.dataset.id - 1]);
setStorageItem('pokemon', favourite);
}
});
I'm trying to look for an id inside an array with objects. The object have an id of 1. My e.target.dataset.id is 1 but it returns false. But when I hardcode the value el.id === 1, it returns true. Am I doing something wrong? Why is it false even though e.target.dataset.id is also 1?
CodePudding user response:
Use el.id == eTargetId
instead of el.id === eTargetId
. (Use just two equal signs, not three.)
e.target.dataset.id
is a JavaScript number 1
. (It's a thing you can do math on, just like 3.141
)
But your HTML element ID is a JavaScript string "1"
. (It's made out of letters, like "I have 1 apple."
).
In JavaScript, there's a fuzzy equality operator ==
, where numbers will be read as if they were strings when compared to strings. So, 1=="1"
is true.
There is also a strict equality operator, where strings and numbers are considered completely different things. So, 1==="1"
is false.