Javascript Data Type How to - Create Array max value function








Question

We would like to know how to create Array max value function.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w w w .  j a  v  a 2  s. c  o  m-->
Array.prototype.max = function() {
var len = this.length;
var max = -1;
for (var i=0; i < len; i++) {
    var val = parseInt(this[i],10);
    if (val > max) {       
        max = val;
    }
}
    return max;
}
var data1Values = ['222','111','444','0','3','0','6','12']
document.writeln(data1Values.max());

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

The code above is rendered as follows: