Javascript 数组原型查找
Javascript array Prototype find
在 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 }
我有一个带有对象数组的购物车 Class,因此,我有一个函数 checkQuantity,它应该 return 任何满足条件的项目。我在需要查找的地方也有相同的功能。
我尝试从 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) 而不是那个方法,它就可以工作。
所以,我的问题是为什么它不起作用?抱歉英语不好。
通过使用this
,除了不使用函数调用的结果外,还需要为Array#find
指定this
。
checkQuantity() {
return this._cart.find(this.itemSearch, this).quantity < this.stockCount();
}
在 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 }
我有一个带有对象数组的购物车 Class,因此,我有一个函数 checkQuantity,它应该 return 任何满足条件的项目。我在需要查找的地方也有相同的功能。
我尝试从 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) 而不是那个方法,它就可以工作。
所以,我的问题是为什么它不起作用?抱歉英语不好。
通过使用this
,除了不使用函数调用的结果外,还需要为Array#find
指定this
。
checkQuantity() {
return this._cart.find(this.itemSearch, this).quantity < this.stockCount();
}