0

我有一个类数组,它们都具有 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 可以为我解决我的问题,那么我宁愿使用它而不是重新发明轮子。

4

1 回答 1

1

lastIndexOf搜索值并且不检查条件,plusthis.isPurchased == true是一个表达式,而不是 lambda。这类似于检查shopItems.lastIndexOf(true)。这不是内置在 JavaScript 中的(甚至在 ES6 中也没有,它提供Array.prototype.find[Index]但没有findLast),所以你必须自己构建它:

function findLast(items, predicate) {
    for (var i = items.length - 1; i >= 0; i--) {
        var item = items[i];

        if (predicate(item)) {
            return item;
        }
    }
}

并将其与回调函数一起使用:

var x = findLast(shopItems, function (item) {
    return item.isPurchased;
});
于 2014-08-31T00:31:21.563 回答