简体   繁体   English

如何在javascript中使用条件索引过滤数组

[英]how to filter an array with index of condition in javascript

Having less background of any coding, am trying to acheive a filtered array from an existing array with indexof condition in javascript. 由于没有任何编码背景,我正在尝试从具有javascript中indexof条件的现有数组中获取经过过滤的数组。

My code: 我的代码:

function CheckIfexists(element) {
  return (element.indexOf(formInput) > -1);
}
var filtered = data.filter(CheckIfexists);
window.alert(filtered[1] + " " + filtered[2] + " " + filtered[3]);

above code is not working 上面的代码不起作用

addl info: 地址信息:

forminput is input taken from form feild. forminput是从表单领域获取的输入。

var formInput = document.getElementById("textReader").value;

data array i got by... 我得到的数据数组...

var data = oRequest.responseText.split("\r\n");

another way i tried is.. 我尝试的另一种方法是..

function CheckIfexists(formInput) {
   for (var i = 0; i < data.length; i += 1) {
       if (data[i].indexOf(formInput) > -1) {
           return false;
       }
   } 
   return true;
}

var filtered = data.filter(CheckIfexists);
window.alert(filtered[1] + " " + filtered[2] + " " + filtered[3]);

the above code is also not working.. 上面的代码也不起作用。


donot doubt about data array and forminput beacuse i checked each element with code, al 不要怀疑数据数组和forminput是因为我用代码检查了每个元素

for(var i=0; i<data.length; i++) {  
    if (data[i] === formInput) {
        alert("You want to retrieve report?");
        didntfind = false;
        break;
    } 
}

     if (didntfind) alert("sorry. part not found");

and i got the ones matching and not matching. 我得到了匹配的和不匹配的。 Addl note: data array has part names, forminput may not be exactly same as element in data array, it can also be partial.. My struggle is to get the filtered ones in new array. 另外请注意:数据数组具有部件名称,forminput可能与数据数组中的元素不完全相同,也可能是不完整的。.我的努力是在新数组中获取过滤后的内容。

Function CheckIfexists will be called on every element in array. 函数CheckIfexists将在数组中的每个元素上调用。 Read and run this code for better understanding: 阅读并运行以下代码以更好地理解:

var data = [1,2,3,4,10];
console.log(data.filter(function (item) { return item > 3; }));

I can see what you trying to do. 我可以看到您想要做什么。 I think, you need to write something like that: 我认为,您需要编写如下内容:

var formInput = document.getElementById("textReader").value;
var data = oRequest.responseText.split("\r\n");

function CheckIfExists(element) {
  return (element === formInput);
};

var filtered = data.filter(CheckIfexists);

And be aware when cheking equality of elements ("1" !== 1, for example) in javascript. 并注意在javascript中检查元素是否相等时(例如“ 1”!== 1)。

var newArray = [];
for(var i=0;i<data.length;i++) {
    var item = data[i];
    if(item.indexOf(formInput1) > -1) {
        newArray.push(item);
    }
});

I got it.. kind of above code is working for me... Thanks again.. 我明白了..上面的代码对我有用...再次感谢..

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

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