Home Search Member List Faq Register Login  
JavaScript Tips
Re: Check whether an item exists in the array

Thread Starter: Karamasoft   Started: 09-18-2007 12:43 PM   Replies: 1
 Karamasoft Support Forums » General Discussions » JavaScript Tips » Re: Check whether an item exists in the array
 Printable Version    « Previous Thread
  18 Sep 2007, 12:43 PM
Karamasoft is not online. Last active: 11/10/2017 3:24:14 PM Karamasoft

Top 10 Posts
Joined on 09-05-2004
Posts 6,818
Check whether an item exists in the array

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


  
  22 Aug 2008, 5:33 PM
Athlon1600 is not online. Last active: 8/22/2008 5:34:22 PM Athlon1600

Not Ranked
Joined on 08-23-2008
United States of America
Posts 1
Re: Check whether an item exists in the array
the idea lightbulb is actually [*letter I*]
  
 Page 1 of 1 (2 items)
Karamasoft Support Forums » General Discussions » JavaScript Tips » Re: Check whether an item exists in the array

You can add attachments
You can post new topics
You can reply to topics
You can delete your posts
You can edit your posts
You can create polls
You can vote in polls
Forum statistics are enabled
Forum is unmoderated

© 2002-2018 Karamasoft LLC. All rights reserved.