【问题标题】:JS filter() function - Is there a way to stop the filter reaching 0 results?JS filter() 函数 - 有没有办法阻止过滤器达到 0 个结果?
【发布时间】:2021-01-04 18:28:16
【问题描述】:

我有以下代码,它循环遍历一个数组,在每个对象的关键字中寻找一个术语。

代码来自本教程,Wix(步骤 7)https://support.wix.com/en/article/velo-tutorial-adding-a-gift-quiz-to-a-wix-stores-site

我需要一些逻辑来防止结束返回 0 结果/空数组,但无法理解循环。理想情况下,当它仍然找到结果时,它会是上一个循环的结果。

// Filter out products that don't match the specified answer.
function filterProductsPerAnswer(quizProducts, answer) {
    // Use the JavaScript filter() function to filter out products that don't match the specified answer.
    const filteredProducts = quizProducts.filter(quizProduct => {
        return quizProduct.keywords.includes(answer)
    });
    // Return the filtered product list.
    return filteredProducts;

}

这让我发疯,因此非常感谢任何帮助!

【问题讨论】:

  • filter() 永远不会返回未定义。在最坏的情况下,它将是一个空数组
  • 为什么你认为结果永远是 undefined 或 0?
  • 如果过滤器过滤掉所有元素,你希望它是什么值?
  • @taplar 你是对的,对不起,它不是未定义的,它只是返回一个空白数组。我宁愿它显示上一个过滤器循环的结果,它没有返回一个空白数组。
  • 在这种情况下,我建议不要更改此方法。相反,调用此方法的方法应该有条件逻辑来检查结果是否为空数组,如果是,则可能忽略它并将其保留为先前的过滤器结果。

标签: javascript filter velo


【解决方案1】:

就像@Taplar 在 cmets 中指出的那样,解决方案可能是您的另一个功能:

    function filteredProductsOrAllProductsIfNoMatch(quizProducts answer) {
        const filteredProducts = filterProductsPerAnswer(quizProducts, answer);
        if (filteredProducts.length === 0) {
            return quizProducts;
        }
        return filteredProducts;
    }
    
    // Your original code:
    // Filter out products that don't match the specified answer.
    function filterProductsPerAnswer(quizProducts, answer) {
        // Use the JavaScript filter() function to filter out products that don't match the specified answer.
        const filteredProducts = quizProducts.filter(quizProduct => {
            return quizProduct.keywords.includes(answer)
        });
        // Return the filtered product list.
        return filteredProducts;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-08
    • 2012-02-03
    • 2019-10-20
    相关资源
    最近更新 更多