我有這個功能返回的數組的最大值:陣列最大值函數給出意想不到的結果
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;
}
當我使用此數組:
var data1Values = ['0','0','0','0','3','0','6','12']
data1Values.max()
返回6代替12。它以某種方式跳過最後一個值。
我已經插入alert(this[i])
和alert(max)
內循環,並且它識別兩個值(12 this[i]
和6爲max
),但它不會進入條件。
這裏發生了什麼?
可以使用'Math.max'用'。適用'從陣列中獲取最大值。 'Math.max.apply(null,data1Values);',所以如果你想要'Array.prototype'上的函數,這樣做...'Array.prototype.max = function(){return Math.max.apply null,this); };' – 2012-04-23 13:56:30
我想知道這是否可能。爲什麼不添加回答? – mplungjan 2012-04-23 16:20:32
@mplungjan:因爲它沒有在技術上回答被問到的問題。只是想提供它作爲一種替代方法。 – 2012-04-23 16:35:29