纯javascipt,筛选器框无法正确过滤

时间:2019-05-28 07:31:08

标签: javascript arrays filter match

我有一个设备阵列,每个设备都有自己的唯一ID,我希望创建一个searchBox来按此ID进行过滤。到目前为止,我已对其进行了部分管理,因此它检查输入中的字符是否与device-id中的字符匹配。但是我不想这样做,例如以下示例:

  

id = 35678; input.value = 5

它不应该工作,因为第一个字符是3

  

id = 35679; input.value = 35

应该与第一个字符相同

问题在匹配/包含功能中,但不知道如何替换它才能使它工作

input_box.addEventListener('keyup', function(){
  var search_result = this.value;
  var device = document.querySelectorAll('[device_id]')
  var array_of_devices = [];
  for (var i = 0; i < device.length; i++) {
       array_of_devices.push(device[i].getAttribute('device_id'))
  }
  array_of_devices.forEach(el => {
         if (!el.match(search_result)) {
           var not_matched = document.querySelector(`[device_id="${el}"]`)
           not_matched.style.display = "none"    
         } else {
          var matched = document.querySelector(`[device_id="${el}"]`)
          matched.style.display = "block"    
        }
     })
 })

3 个答案:

答案 0 :(得分:2)

您可以使用startsWith代替匹配

let arr = ['35678', '451234', '45454', '56565']

let find = (value) =>{
  return arr.filter(id=> id.startsWith(value))
}

console.log(find(5))
console.log(find(35))
console.log(find(46))

答案 1 :(得分:1)

代替使用.match,您可以简单地使用.indexOf并检查索引,如果索引为0,则输入的字符串从头开始与设备名称匹配。

array_of_devices.forEach(el => {
  // Condition below is changed to use indexOf
  if (el.indexOf(search_result) === 0) {
    var not_matched = document.querySelector(`[device_id="${el}"]`)
    not_matched.style.display = "none"
  } else {
    var matched = document.querySelector(`[device_id="${el}"]`)
    matched.style.display = "block"
  }
});

我建议您根据搜索字符串构建一串设备元素,并将其添加到DOM中,而不要修改显示属性。这会使您花费大量的DOM操作,而这些操作在计算上很繁琐。

答案 2 :(得分:0)

请注意,数组中的每个ID均应为字符串

const ids = ['3575', '5555']
const found = value => ids.filter(i => i.indexOf(value, 0) === 0)
console.log(found(5));
console.log(found(35));