Return the item at the given index in the array, allowing for positive and negative integers. Negative integers count back from the last item in the 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
/** | |
* Return the item at the given index in the array, allowing for positive and | |
* negative integers. Negative integers count back from the last item | |
* in the array. | |
* | |
* {@link https://gist.github.com/kieranbarker/1bb4ae463f3cd8138b4805983de49f4d} | |
* | |
* @param {Array} array The array | |
* @param {Number} index The index | |
* @returns {*} The item at the given index | |
*/ | |
function array_at(array, index) { | |
if (!Array.isArray(array)) { | |
throw new TypeError('Expected first argument to be an array.'); | |
} | |
if (typeof index !== 'number') { | |
throw new TypeError('Expected second argument to be a number.'); | |
} | |
return index >= 0 ? array[index] : array[array.length + index]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the blog post:
https://kbarker.dev/blog/the-array-at-method-in-vanilla-js/