JavaScript 数组包含

Avatar of Chris Coyier
Chris Coyier

Javascript 对象非常棒,但有时它们缺少一些有用的函数/方法。上面的示例是使用数组。了解你的数组中是否包含一个项目非常有用。当然,你可以编写一个接受数组和你要检查的项目的函数,但向 Array 对象添加 contains( item ) 方法要干净得多。

扩展 JavaScript 数组

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

用法

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}