Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript数组中搜索值?_Javascript - Fatal编程技术网

如何在JavaScript数组中搜索值?

如何在JavaScript数组中搜索值?,javascript,Javascript,我正在学习JavaScript,我遇到了这个问题。我想使用document.formName.elementName.value捕获输入值,并将该值与数组对象的实例进行比较。如果该值存在,它将抛出警报 我想这已经被问了几千次了: if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){ alert("You did something wrong!"); } 注意旧版本的IE不知道indexOf。(但谁需要

我正在学习JavaScript,我遇到了这个问题。我想使用
document.formName.elementName.value
捕获输入值,并将该值与数组对象的实例进行比较。如果该值存在,它将抛出警报

我想这已经被问了几千次了:

if(myFancyArray.indexOf(document.formName.elementName.value) !== -1){
   alert("You did something wrong!");
}
注意旧版本的IE不知道
indexOf
。(但谁需要IE?

您可以使用indexOf()函数,只需执行以下操作:
array.indexOf(“字符串”)
如果找不到项目,则返回-1,否则仅返回位置。 这里有一个链接。

使用

测试用例:

search(["a","b"], "a"); // true
search(["a","b"], "c"); //false

您可以向JavaScript的数组中添加一个方便的方法

Array.prototype.includes = function(element) { 
    var found = false;
    for (var i = 0; i < this.length; i++) { 
        if (this[i] == element)  {
            found = true;
        }
    }
    return found;
}
Array.prototype.includes = function(element) { 
    var found = false;
    for (var i = 0; i < this.length; i++) { 
        if (this[i] == element)  {
            found = true;
        }
    }
    return found;
}
var myArray = [0,1,"hello","world"];

console.log(myArray.includes("hello")); //prints true
console.log(myArray.includes(10)); //prints false