Javascript Data Type How to - Get array element value from an offset number








Question

We would like to know how to get array element value from an offset number.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--from   w w  w. j a  v  a 2 s .c  o  m-->
Array.prototype.at = function(index) {
    return index > this.length ? this[0] : this[index];
};
var list = ['first', 'second', 'third'];
document.write(list.at(1));
document.write('<br />');
document.write(list.at(5));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: