I have this function for returning the maximum value of an array:
Array.prototype.max = function() {
var max = this[0];
var len = this.length;
for (var i = 1; i < len; i++)
{
if (this[i] > max)
{
max = this[i];
}
}
return max;
}
When I use this array:
var data1Values = ['0','0','0','0','3','0','6','12']
data1Values.max() returns 6 instead of 12. It somehow skips the last value.
I’ve inserted alert(this[i]) and alert(max) inside the loop, and it recognizes both values (12 as this[i] and 6 as max) but it wont enter the condition.
What is happening here ?
You are comparing strings. “2” is greater than “1000”
Change to numbers or add parseInt(this[i],10)
DEMO