简体   繁体   English

将过滤器与 vainilla JS 结合使用,逻辑问题

[英]Combining filters with vainilla JS, issue with logic

I'm practising with DOM manipulation, APIs and filters;我正在练习 DOM 操作、API 和过滤器; I am creating a table with JavaScript, I've created some checkboxes and a drop-down to filter the data, and now trying to combining both.我正在使用 JavaScript 创建一个表,我创建了一些复选框和一个下拉列表来过滤数据,现在尝试将两者结合起来。

So far, I managed to make it work for 3 out of the 4 possible cases, but I don't see what I am missing on the fourth.到目前为止,我设法使其适用于 4 种可能情况中的 3 种,但我没有看到我在第四种情况下遗漏了什么。

This my filtering function:这是我的过滤功能:

function filtering(data, optionChecked, harvestTypeValue) {
  let filteredResults = [];
  if (optionChecked.length === 0 && harvestTypeValue === 'all') {
    // No checkboxes checked and dropdown with option "All" selected. Working
    filteredResults = data
  } else if (optionChecked.length === 0 && harvestTypeValue != 'all') {
    for (let i = 0; i < data.length; i++) {
      if (data[i]['Harvest Type'] == harvestTypeValue) {
        // No checkboxes checked and dropdown with any option selected. Working:
        filteredResults.push(data[i]);
      }
    }
  } else if (optionChecked.length != 0 && harvestTypeValue === 'all') {
    for (let i = 0; i < data.length; i++) {
      if (optionChecked.includes(data[i]['NOAA Fisheries Region'])) {
        // Any checkbox checked and dropdown with All. Working:
        filteredResults.push(data[i]);
      }
    }
  } else {
    for (let i = 0; i < data.length; i++) {
      if (filteredResults.includes(data[i]['NOAA Fisheries Region']) && data[i]['Harvest Type'] == harvestTypeValue) {
        // Any/some checkboxes checked and dropdown with any option selected. NOT working.
        // Getting an empty object:
        filteredResults.push(data[i]); 
      }
    }
  }
  createTable(filteredResults)
}

It might be a small thing, or a big fail in my logic, but I am clueless and almost giving up.这可能是一件小事,也可能是我逻辑上的大失败,但我一无所知,几乎要放弃了。

I would also appreciate any suggestions to make that code shorter.我也很感激任何使代码更短的建议。

last Else , instead of最后一个 Else ,而不是

if (filteredResults.includes(data[i]['NOAA Fisheries Region']) && data[i]['Harvest Type'] == harvestTypeValue)

should be :应该 :

if (optionChecked.includes(data[i]['NOAA Fisheries Region']) && data[i]['Harvest Type'] == harvestTypeValue)

Now it makes sense and both filters work combined in all possible ways现在这是有道理的,两个过滤器以所有可能的方式结合使用

amazing how blind (and stupid) I was...令人惊讶的是我是多么盲目(和愚蠢)......

Thanks to all!谢谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM