I want to make a function that works like this:
function arraySearch(array, valuetosearchfor)
{
// some code
}
if it finds the value in the array, it will return the key, where it found the value. If there is more than one result (more than one key), or no results at all (nothing found), then the function will return FALSE.
I found this code:
function arraySearch(arr,val)
{
for (var i=0; i<arr.length; i++)
{
if (arr[i] == val)
{
return i;
}
else
{
return false;
}
}
}
and used it like this:
var resultofarraycheck = arraySearch(board, chosen);
if (resultofarraycheck === false)
{
document.getElementById(buttonid).value;
chosen = 0;
}
But it doesn't seem to work. When it should find something, it returns false instead of the key (i).
How can I fix this, or what am I doing wrong?
Thanks, and I'm sorry if my English wasn't clear enough.
function arraySearch(arr,val) {
for (var i=0; i<arr.length; i++)
if (arr[i] === val)
return i;
return false;
}
You can use indexOf to get key jsfiddle
if(!Array.prototype.indexOf){
Array.prototype.indexOf = function(val){
var i = this.length;
while (i--) {
if (this[i] == val) return i;
}
return -1;
}
}
var arr = ['a','b','c','d','e'];
var index = arr.indexOf('d'); // return 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With