在developer.mozilla上,我找到了一个使用数组查找的示例:
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function isCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }我有一个带有对象数组的cart Class,因此,我有一个函数checkQuantity,它应该返回满足条件的任何商品。此外,我有相同的功能,我需要找到。
我试着在mozilla中实现这种方法,我喜欢这样:
itemSearch(item) {
return item.id === this.id &&
item.color === this.color &&
item.size === this.size
} // method which i need我是这样使用它的:
checkQuantity() {
return this._cart.find(this.itemSearch()).quantity < this.stockCount();
}但是,我知道它必须找到,因为如果我使用.find(element => conditions)而不是那个方法,它就能工作。
所以,我的问题是,为什么它不起作用?对不起,我的英语不好。
发布于 2021-04-10 19:58:27
通过使用this,除了不使用函数调用的结果之外,还需要为Array#find指定this。
checkQuantity() {
return this._cart.find(this.itemSearch, this).quantity < this.stockCount();
}https://stackoverflow.com/questions/67034075
复制相似问题