Javascript对象确实很棒,但是有时它们缺少一些有用的小功能/方法。 上面的例子是关于数组的。 很高兴知道数组中是否包含某个项目。 好了,您可以编写一个函数,该函数采用要检查的数组和项目,但是将contains(item)方法添加到Array对象要干净得多。
扩展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
}
翻译自: https://css-tricks.com/snippets/javascript/javascript-array-contains/