英文:
If I set the value to find as a variable, why doesn't it work?
问题
当使用数字1调用findProd函数时,一切都正常。但是,如果我用idToFind变量替换数字1,控制台会输出undefined。为什么会发生这种情况?
P.S. 在我的文件中,如果我打印idToFind,结果是1。需要使函数的比较值动态化。
英文:
When calling the findProd function with the number 1, everything works correctly. However, if I replace the number 1 with the idToFind variable, the console outputs undefined. Why is this happening?
P.S. in my file, if I print idToFind, the result is 1.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
function findProd(product) {
return product.id === 1;
}
const result = array.find(findProd);
console.log(result);
})
});
I need to make the comparison value of the function dynamic.
答案1
得分: 2
因为event.target.dataset.id
是一个字符串。你所使用的严格比较运算符首先比较数据类型,所以1 === '1'
的结果是false
。
请注意,你可以使用一元运算符+
将字符串值转换为数字值。然后1 === 1
就会得到true
,因此,你的find
函数将按预期工作。
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = +event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
const result = array.find((product) => product.id === idToFind);
console.log(result);
})
});
此外,从代码的可读性角度来看,将标识符在变量初始化期间转换为数字会使代码更加清晰。
你可能想要阅读更多关于严格相等性 ===
的信息。
英文:
It's because the event.target.dataset.id
is a string. The strict comparison operator you use compares types first, so 1 === '1'
results in false
.
Notice how you can convert string value to a number value with an unary +
. Then 1 === 1
would result in true
and in consequence, your find
function will work as expected.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
function findProd(product) {
return product.id === +idToFind;
}
const result = array.find(findProd);
console.log(result);
})
});
Also, the code would benefit in readability from using an array function and converting the identifier to number during the variablie initialization.
addToCartButtons.forEach(button => {
button.addEventListener('click', (event) => {
const idToFind = +event.target.dataset.id;
let array = [{id: 1, name: 'mattia'}, {id: 2, name: 'cesare'}];
const result = array.find((product) => product.id === idToFind);
console.log(result);
})
});
You may want to read more about the strict equality ===
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论