Skip to content

Instantly share code, notes, and snippets.

@KryptikOne
Last active June 19, 2019 21:38
Show Gist options
  • Select an option

  • Save KryptikOne/d08e170492f9f785592bcd8d7d1f08de to your computer and use it in GitHub Desktop.

Select an option

Save KryptikOne/d08e170492f9f785592bcd8d7d1f08de to your computer and use it in GitHub Desktop.
/**
* A function to determine if an array contains an item
* @param needle - [Number||String] - The array to search through
* @returns [boolean] - Returns true or false
*/
function arrContainsItem(needle) {
var findNaN = needle !== needle; // Per spec, the way to identify NaN is that it is not equal to itself
var indexOf;
if(!findNaN && typeof Array.prototype.indexOf === 'function') {
indexOf = Array.prototype.indexOf;
} else {
indexOf = function(needle) {
var i = -1, index = -1;
for(i = 0; i < this.length; i++) {
var item = this[i];
if((findNaN && item !== item) || item === needle) {
index = i;
break;
}
}
return index;
};
}
return indexOf.call(this, needle) > -1;
}
// Usage
var arrayToCheck = ["string", 24];
console.log(arrContainsItem.call(arrayToCheck, itemToCheckFor));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment