Saturday 1 February 2014

array.contains(obj) in JavaScript

Modern browsers have Array#indexOf, which does exactly that; this is in the new(ish) ECMAScript 5th edition specification, but it has been in several browsers for years. Older browsers can be supported using the code listed in the "compatibility" section at the bottom of that page.
jQuery has a utility function for this:
$.inArray(value, array)
It returns the index of a value in an array. It returns -1 if the array does not contain the value.
jQuery has several useful utility functions.
An excellent JavaScript utility library is underscore.js:
Some other frameworks:
Notice how some frameworks implement this as a function. While other frameworks add the function to the array prototype.

Languages that compile to javascript

In coffeescript, the in operator is the equivalent of contains:
a = [1, 2, 3, 4]
alert
(2 in a)
Dart:
var mylist = [1, 2, 3];
assert(mylist.contains(1));
assert(mylist.indexOf(1) == 0);

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More