使用JavaScript筛选API产品时价格范围过滤逻辑失效问题求助
使用JavaScript筛选API产品时价格范围过滤逻辑失效问题求助
我正在开发一个基于API产品数据的筛选功能,核心是用JavaScript的filter()方法结合HTML中的价格复选框来过滤产品,但遇到了价格范围判断的问题:
- 当我只用单条件判断
if ((product.price < checkboxesValues[j][1]))时,筛选是有效的 - 但换成价格区间判断时,完全没有筛选效果,我试过两种写法:
if ((product.price >= checkboxesValues[j][0]) && (product.price <= checkboxesValues[j][1]))if (checkboxesValues[j][0] <= product.price <= checkboxesValues[j][1])
这个判断逻辑是写在一个辅助函数里的,以下是我的完整代码:
HTML 代码
<!-- Price Checkboxes--> <div class="price-checkboxes"> <h4>Price: </h4> <input type="checkbox" id="price1" name="price1" value="0,200"> <label for="price1">0-200 EUR</label><br> <input type="checkbox" id="price2" name="price2" value="200,400"> <label for="price2">200-400 EUR</label><br> <input type="checkbox" id="price3" name="price3" value="400,600"> <label for="price3">400-600 EUR</label><br> <input type="checkbox" id="price4" name="price4" value="600,800"> <label for="price4">600-800 EUR</label><br> <input type="checkbox" id="price5" name="price5" value="800,1000"> <label for="price5">800-1000 EUR</label><br> </div>
JavaScript 代码
const isInCheckboxRange = (products) => { //create a NodeList of the selected checkboxes const checkboxes = document.querySelectorAll("input[type='checkbox']:checked"); console.log("checkboxes: ", checkboxes); //transform the NodeList into an Array of the selected checkboxes const checkboxesArray = Array.from(checkboxes); console.log("checkboxesArray: ", checkboxesArray); //map the values in the Array into a new Array just with the selected checkboxes values in integers const checkboxesValues = checkboxesArray.map((checkbox) => { //return a number array from the previous string's value const stringArray = checkbox.value.split(","); return stringArray.map(Number); }) console.log("checkboxesValues: ", checkboxesValues); const filteredProductPrices = products.filter((product) => { for (let j = 0; j < checkboxesValues.length; j++) { // console.log("product price: ", product.title, product.price, "checkboxesValues[j][0]: ", checkboxesValues[j][0], "checkboxesValues[j][1]: ", checkboxesValues[j][1]); if ((product.price < checkboxesValues[j][1])) { // if ((product.price >= checkboxesValues[j][0]) && (product.price <= checkboxesValues[j][1])) { // if (product.price > checkboxesValues[j][0] && product.price < checkboxesValues[j][1]) { // if (checkboxesValues[j][0] <= product.price <= checkboxesValues[j][1]) { console.log("product price: ", product.title, product.price, "checkboxesValues[j][0]: ", checkboxesValues[j][0], "checkboxesValues[j][1]: ", checkboxesValues[j][1]); return true; } } return false; }); console.log("Filtered Products: ", filteredProductPrices); return filteredProductPrices; }
我也尝试过调整return true;在循环中的位置,但都没有解决问题,希望大家能帮我找出问题所在。
备注:内容来源于stack exchange,提问作者Diogo Dust
相关产品推荐
相关产品推荐

