JavaScript non dispone di un metodo nativo per sapere se una voce è presente o meno in un array. Fortunatamente possiamo crearne uno noi.
Il seguente metodo viene aggiunto a tutti gli array usando la proprietà prototype
dell'oggetto Array
:
if(typeof Array.prototype.contains !== 'function') {
Array.prototype.contains = function ( needle ) {
for (i in this) {
if (this[i] == needle) {
return true;
}
}
return false;
}
}
Esempio d'uso:
var arr = ['a', 'b', 'c'];
console.log(arr.contains('c')); // true