[英]How to check if a string or a number exists inside an array Javascript
I have a functions which asks the users to write their favorites animals ant then stores it in an array called animals.When a user executes the function I want to check if the animal he wants is inside the array and if yes to show the index of the animal(for example:The animal you entered is already in the array.Its index number is...).Any ideas? 我有一个函数要求用户编写自己喜欢的动物蚂蚁,然后将其存储在称为动物的数组中。当用户执行该函数时,我要检查他想要的动物是否在数组中,如果是,则显示索引动物(例如:您输入的动物已经在数组中了,它的索引号是...)。有什么想法吗?
var animals=[]
function anim(){
var ani=prompt("Give me an animal you like");
animals.push(ani);
}
You can iterate across the array and with regex to get accurate result regard less input case 您可以使用正则表达式遍历整个数组,以较少的输入情况获得准确的结果
function searchArr(arr, q){
for (i = 0; i < arr.length; i++){
patt = new RegExp(q,"i");
if (patt.test(arr[i])) return i;
}
return false;
}
Testing Code: 测试代码:
animals = new Array('dog', 'cat', 'camel', 'deer');
q = prompt("Enter Animal Name");
r = searchArr(animals,q);
alert(r)
if (r || r ===0){
alert("Animal found and its index " + r)
}
else{
alert("Not found")
}
Demo: http://jsbin.com/jolaqiduka/1/ 演示: http : //jsbin.com/jolaqiduka/1/
you can find out if a value is inside of an array by using indexOf()
. 您可以使用
indexOf()
来确定值是否在数组内。
for example: animals.indexOf('dog');
例如:
animals.indexOf('dog');
this will return the index of the string 'dog'. 这将返回字符串“ dog”的索引。 if it doesn't exist, it will return a value of -1.
如果不存在,它将返回值-1。
var animals= new Array('dog');
var ani=prompt("Give me an animal you like");
if(animals.indexOf(ani) >= 0 ){
alert(animals.indexOf(ani));
}else{
animals.push(ani);
}
This this way 这样
var animals=[]
function anim() {
var ani = prompt("Give me an animal you like");
// The function returns a position of an input element (in array) begins from the 0
// or -1 if the element is not exists in the array
if (animals.indexOf(ani) > -1)
alert('Already in');
else
animals.push(ani);
}
Next fiddle may help: http://jsfiddle.net/8g5gpqx2/ 下一个小提琴可能会有所帮助: http : //jsfiddle.net/8g5gpqx2/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.