我有一个类数组,它们都具有 isPurchased 属性,我想返回数组中值设置为 true 的最后一项。
function ShopItem = new function(id, name, isPurchased) {
this.id = id;
this.name = name;
this.isPurchased = isPurchased;
}
var apple = ShopItem(1, "Apple", false);
var banana = ShopItem(2, "Banana", true);
var pear = ShopItem(3, "Pear", false);
var shopItems = [apple, banana, pear];
var x = shopItems.lastIndexOf(this.isPurchased == true);
console.log(x);
当我做 console.log(x); 我希望它返回香蕉类。
一切正常,直到我尝试找到最后一个项目,为此我尝试使用:
var x = shopItems.lastIndexOf(this.isPurchased == true);
但它返回-1。
编辑:
我有办法通过使用代码来解决解决方案:
var y = null;
for(var o in shopItems) {
if(shopItems[o].isPurchased == true) {
y = shopItems[o];
}
}
console.log(y);
但如果 lastIndexOf 可以为我解决我的问题,那么我宁愿使用它而不是重新发明轮子。