为什么这个array.filter总是不返回任何内容

Why does this array.filter always return nothing?

本文关键字:返回 任何内 array filter 为什么      更新时间:2023-09-26

为什么这个过滤器从不返回任何对象?

NewHashMap.prototype.remove = function (keys, obj) {
    // snip
    var myEntries = this.entries;
    var filteredEntries = myEntries.filter(
        function(entry){
            //me.isContainedBy(entry, keys) &&
            //entry.obj === obj
            true;
        });
    console.debug("entries ",  myEntries.length);
    console.debug("filtered ", filteredEntries.length);
    // snip
}

再进一步,我在不同的上下文中使用它,它是有效的
您还可以看到,我注释掉了实际的过滤器要求,并用一个简单的True替换了它们。同样的事情。

我猜这是一个上下文问题,但我不知道在哪里。

您的true不会执行任何操作,除非您从匿名函数中return

var filteredEntries = myEntries.filter(
    function(entry){
        //me.isContainedBy(entry, keys) &&
        //entry.obj === obj
        return true;
});

或者使用您的实际过滤代码:

var filteredEntries = myEntries.filter(
    function(entry){
        return me.isContainedBy(entry, keys) && entry.obj === obj
});

您需要从回调函数中return一个布尔值:

var filteredEntries = myEntries.filter(
        function(entry){
            //me.isContainedBy(entry, keys) &&
            //entry.obj === obj
            return true;
        });