Created
January 8, 2019 10:52
-
-
Save john-yuan/8a5c01b6318ad515091672861d52df9d to your computer and use it in GitHub Desktop.
Get the index of the element in the given array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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