Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function inArray

I need a javascript function that can take in a string and an array, and return true if that string is in the array..

 function inArray(str, arr){
   ...
 }

caveat: it can't use any javascript frameworks.

like image 941
RobKohr Avatar asked May 20 '09 23:05

RobKohr


People also ask

What is inArray in JavaScript?

In JavaScript, the array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

What is inArray?

An array is a collection of items of same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).

How do you check if a value exists in an array JavaScript?

The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.

How do you check if a string exists in an array JavaScript?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.


1 Answers

You could just make an array prototype function ala:

Array.prototype.hasValue = function(value) {
  var i;
  for (i=0; i<this.length; i++) { if (this[i] === value) return true; }
  return false;
}

if (['test'].hasValue('test')) alert('Yay!');

Note the use of '===' instead of '==' you could change that if you need less specific matching... Otherwise [3].hasValue('3') will return false.

like image 156
gnarf Avatar answered Oct 13 '22 11:10

gnarf