问题描述
我有以下代码,它循环遍历一个数组,在归因于每个对象的关键字中查找一个术语。
代码来自 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;
}
这让我很生气,所以非常感谢任何帮助!
解决方法
就像@Taplar 在评论中指出的那样,解决方案可能是您的另一个功能:
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;
}