我只想显示最小数,但它却显示最小数和无穷大,为什么我得到无穷大?我该怎么摆脱它?
var repeat, studentArr = [], markArr = [];
while (repeat !== 'n' && repeat !== 'N'){
studentArr.push(prompt("Enter Student Name: "));
markArr.push(parseInt (prompt("Enter Student mark: ")));
repeat = prompt ("Do you want to enter another student: y/n");
}
var largest = max(markArr);
Array.prototype.max = function() {
return Math.max.apply(Math, markArr);
};
Array.prototype.min = function() {
return Math.min.apply(Math, markArr);
};
var min = Math.min.apply(Math, markArr),
max = Math.max.apply(Math, markArr);
document.write(min);发布于 2014-03-31 02:22:08
Array.prototype.max = function() {
return Math.max.apply(Math, markArr);
};
Array.prototype.min = function() {
return Math.min.apply(Math, markArr);
};这些不是很好的原型定义;它们被绑定在一个对象上!让他们用this代替。
Array.prototype.max = function() {
return Math.max.apply(Math, this);
};
Array.prototype.min = function() {
return Math.min.apply(Math, this);
};除此之外,在您调用max以获得latest (应该是undefined)时,它不是一个函数,您也没有使用这些函数。我很惊讶你能得到无穷无尽。
var min = markArr.min();
var max = markArr.max();
document.write(min);或者我们可以停止使用原型;这把小提琴对我来说很好。
发布于 2014-03-31 02:29:36
您需要传递数组本身。如果在数组上调用该方法,则该方法中的该方法将是该数组,因此:
Array.prototype.max = function() {
return Math.max.apply(Math, this);
};对其他方法也要这样做。
请注意,扩展Array.prototype将影响数组上的for..in枚举,因此需要hasOwnProperty测试来筛选出原型上的可枚举属性。
发布于 2015-05-17 11:22:28
当您在非整数中使用Infinity时也会引发Math.max问题.
那么,在调用map之前最好先调用max:
即:
urArray.map(function(e){return parseInt(e);/*or parseFloat()*/}).max()https://stackoverflow.com/questions/22752645
复制相似问题