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