简体   繁体   English

在JavaScript中使用for循环在数组中搜索值

[英]searching for value in an array with a for loop in javascript

I am searching for an value from an array in javascript and this is my code. 我正在从JavaScript中的数组中搜索值,这是我的代码。

HTML 的HTML

<input type="text" placeholder="enter here" id="textvalue">
<button id="checkbutton">check</button>

Javascript Java脚本

let arr = ["boy", "cat", "dog"];
let txtval = document.querySelector("#textvalue");
let chkbutt = document.querySelector("#checkbutton");

chkbutt.addEventListener("click", arraycheck);

function arraycheck () {
 for(i=0; i<arr.length; i++) {
   if(txtval.value==arr[i]) {
     alert("match found for " + txtval.value)
     }
  else {
   alert("its not there")
    }
 }
}

At the moment, I keep getting alert saying "its not there" when I enter "dog". 此刻,当我输入“ dog”时,我总是保持警惕,说“它不在那里”。 It prints "its not there" twice and then prints "match found for dog". 它打印两次“不存在”,然后打印“找到匹配的狗”。 I would like the alert to show only if the word does not exist in the array. 我希望仅在单词不存在于数组中时显示警报。 I know it is doing this because I have the if statement in the for loop and each time if the index of the array does not match, it shows the alert. 我知道这样做是因为在for循环中有if语句,并且每次数组的索引不匹配时,都会显示警报。 But how do I do it? 但是我该怎么办呢?

You can simplify using indexOf method, 您可以使用indexOf方法进行简化,

if(arr.indexOf(txtval.value) > -1)

DEMO 演示

 let arr = ["boy", "cat", "dog"]; let txtval = document.querySelector("#textvalue"); let chkbutt = document.querySelector("#checkbutton"); chkbutt.addEventListener("click", arraycheck); function arraycheck () { if(arr.indexOf(txtval.value) > -1) { alert("match found"); } else { alert("its not there"); } } 
 <input type="text" placeholder="enter here" id="textvalue"> <button id="checkbutton">check</button> 

You're alerting on every pass of the loop. 您会在循环的每一次通过中发出警报。 Instead, use a flag and alert at the end: 相反,请使用标志并在末尾发出警报:

function arraycheck () {
    var found = false; // *** The flag
    for (var i=0; !found && i<arr.length; i++) {
//                ^^^^^^^^^---- *** Stop looping if we find it
        if (txtval.value==arr[i]) {
            found = true; // *** Set the flag, it was found
        }
    }
    if (found) {
        alert("match found for " + txtval.value);
    } else {
        alert("its not there");
    }
}

or we could just use the result of the == directly: 或者我们可以直接使用==的结果:

function arraycheck () {
    var found = false; // *** The flag
    for (var i=0; !found && i<arr.length; i++) {
//                ^^^^^^^^^---- *** Stop looping if we find it
        found = txtval.value==arr[i]; // *** Set the flag if it was found
    }
    if (found) {
        alert("match found for " + txtval.value);
    } else {
        alert("its not there");
    }
}

(Side note: Unless you're declaring i somewhere you haven't shown, your code is falling prey to The Horror of Implicit Globals [that's a post on my anemic little blog] . Declare your variables. I've added declarations for i in the examples above.) (旁注:除非您在未显示的地方声明i否则您的代码将成为“隐式全球性恐怖”的猎物[这是我贫乏的小博客上的帖子] 。声明您的变量。我为i添加了声明在上面的示例中。)


However , there's already a function for that (two, in fact): includes (on newer JavaScript engines) and indexOf (on older ones): 但是 ,已经有一个功能(实际上是两个): includes (在较新的JavaScript引擎上)和indexOf (在较旧的引擎上):

function arrayCheck() {
    var found = arr.includes(txtval.value); // <===
    if (found) {
        alert("match found for " + txtval.value)
    } else {
        alert("its not there")
    }
}

or the found part of that on older browsers using indexOf : 或使用indexOf在旧版浏览器中found部分:

var found = arr.indexOf(txtval.value) != -1;

In a comment you asked: 在评论中,您询问:

I was wondering if you could also stop the loop in my code using "return"? 我想知道您是否还可以使用“返回”来停止代码中的循环?

Yes, that's yet another way to do it in this specific case, since exiting the function (with return ) exits the loop: 是的,在这种特定情况下,这是另一种方法,因为退出函数(带有return )会退出循环:

function arraycheck () {
    for (var i=0; i<arr.length; i++) {
        if (txtval.value==arr[i]) {
            alert("match found for " + txtval.value);
            return;
        }
    }
    alert("its not there");
}

Try the following with Array's includes() in a more simpler and cleaner way: 以更简单,更简洁的方式尝试使用Array的includes()进行以下操作:

 let arr = ["boy", "cat", "dog"]; let txtval = document.querySelector("#textvalue"); let chkbutt = document.querySelector("#checkbutton"); chkbutt.addEventListener("click", arraycheck); function arraycheck () { if(arr.includes(txtval.value)){ alert("match found for " + txtval.value) } else{ alert("its not there") } } 
 <input type="text" placeholder="enter here" id="textvalue"> <button id="checkbutton">check</button> 

Create a variable that will turn to true when a match is found. 创建一个变量,当找到匹配项时该变量将变为true。 Then if after the loop the variable is still false, then no match has been found. 然后,如果循环后变量仍为false,则找不到匹配项。

Or better yet, use lodash filter. 或者更好的是,使用lodash过滤器。 It simplifies the looping process. 它简化了循环过程。

You can try to find the index of your txtval.value in the array by using JavaScript Array indexOf() method. 您可以尝试使用JavaScript Array indexOf()方法在数组中查找txtval.value的索引。

It takes a input value and output the index number of that value in the Array if the value exists. 它接受一个输入值,并在该值存在的情况下在Array输出该值的索引号。

As javascript array index starts from 0, so if the value exists, the method will return integer(index in the array) value that is greater than -1. 由于javascript数组索引从0开始,因此,如果该值存在,则该方法将返回大于-1的整数(数组中的索引)值。

So, in your case, 所以,就您而言,

function arraycheck () {
    var index = arr.indexOf(txtval.value);
    if(index > -1){
        //alert for found match
    }else{
        //alert for no match found
    }
}

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

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