JavaScript Tips
Topic: Re: Check whether an item exists in the array
Karamasoft Support Forums

Page 1 of 1 (2 items)

Posted by Karamasoft on 09-18-2007 12:43 PM

JavaScript Array object does not provide a built-in method to return whether a given value exists in the array. However, we can add a prototype method to extend Array functionality by adding a method to return whether the array has the given value.

Array.prototype.has = function(value) {

var i;

for (var i = 0, loopCnt = this.length; i < loopCnt; i++) {

if (thisIdea === value) {

return true;



return false;


Note that this method uses === operator to check if the value is identical (is equal to and is of the same type) to the value in the array. If you want to check only whether they are equal, you should replace === with == operator (is equal to).

Then, we can use this method as follows:

var arr = new Array();

arr[0] = 'test';

alert(arr.has('test')); // Should display true

alert(arr.has('test2')); // Should display false

Posted by Athlon1600 on 08-22-2008 5:33 PM
the idea lightbulb is actually [*letter I*]