1

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
2
  • you should post an example .. a small code Commented Sep 16, 2012 at 6:40
  • I'm sorry if i misunderstood your question, but shouldn't just be array[index] === value? Commented Sep 16, 2012 at 6:44

3 Answers 3

4

try this:

function check(array, index, value) {
    if(index < 0 || index >= array.length) {
         return false;
    }
    return array[index] === value;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Update 2022

With ES2022 you can use Array.prototype.at():

function isValueAtIndex(array, index, value) {
    return array.at(index) === value
}
  • You can check from the end with negative index.
  • You do not have to check length since at will return undefinded if the given index can not be found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.