Skip to content

Instantly share code, notes, and snippets.

@john-yuan
Created January 8, 2019 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save john-yuan/8a5c01b6318ad515091672861d52df9d to your computer and use it in GitHub Desktop.
Save john-yuan/8a5c01b6318ad515091672861d52df9d to your computer and use it in GitHub Desktop.
Get the index of the element in the given array
/**
* Get the index of the element in the given array
*
* @param {any} element the element to find
* @param {any[]} array the array to be searched
* @param {number} [fromIndex=0] the array index at which to begin the search
* @returns {number} returns the index of the element. if the element is not found, -1 is returned.
*/
var indexOf = function (element, array, fromIndex) {
if (typeof Array.prototype.indexOf === 'function') {
indexOf = function (element, array, fromIndex) {
fromIndex = typeof fromIndex === 'number' ? fromIndex : 0;
return array.indexOf(element, fromIndex);
};
} else {
indexOf = function (element, array, fromIndex) {
var i = typeof fromIndex === 'number' ? fromIndex : 0;
var l = array.length;
while (i < l) {
if (element === array[i]) {
return i;
}
i += 1;
}
return -1;
};
}
return indexOf(element, array, fromIndex);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment