Reputation: 317
I have an array with 144 indexes, that I fill with data from a form. I want to check if a certain index contains a certain value, and I don't know if such function exists in JavaScript, or how to make said function.
Can you help me make a function that gets an array, a certain index and a certain value as parameters and return true if it exists?
An example:
var board = new Array();
board.push('X');
board.push('O');
function inArrayatindex(array, index, value)
{
/* if(certain code that i need help with...)
{
return true;
}
}
inArrayatindex(board, 2, 'O'); //returns true
inArrayatindex(board, 2, 'o'); // returns false
inArrayatindex(board, 3, 'X'); // returns false
Upvotes: 1
Views: 1801
Reputation: 2534
With ES2022 you can use Array.prototype.at()
:
function isValueAtIndex(array, index, value) {
return array.at(index) === value
}
at
will return undefinded
if the given index can not be found.Upvotes: 0
Reputation: 1716
I think that is what you need,
function inArray(array,valueToMatch){
var myArray = array
var index = -1;
for(int i=0;i<myArray.length;i++){
if(myArray[i].match(valueToMatch)){
index = i;
}
}
return index;
}
note : array parameter your 144 index array
valueToMatch parameter is the value you search for
Upvotes: 0
Reputation: 4434
try this:
function check(array, index, value) {
if(index < 0 || index >= array.length) {
return false;
}
return array[index] === value;
}
Upvotes: 4