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.
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.
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).
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.
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.
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.
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