你好我有一个数组,我似乎无法获得它的最小值和最大值idk这里有什么问题是我的代码
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");
}
function min (markArr){
var min = Number.Max_Value;
for(var i = 0; i < markArr.length; i++){
if(number(markArr[i]) < min)
min = number(markArr[i]);
}
return markArr;
}
var smallest = min(markArr);
function max (markArr){
var max = Number.Max_Value;
for(var i = 0; i > markArr.length; i++){
if(number(markArr[i]) < max)
max = number(markArr[i]);
}
return markArr;
}
var largest = max(markArr);
document.write(largest);
答案 0 :(得分:0)
您可以从Javascript扩展Array
类型,例如:
Array.prototype.min = function(comparer) {
if (this.length === 0) return null;
if (this.length === 1) return this[0];
comparer = (comparer || Math.min);
var result = this[0];
for (var i = 1; i < this.length; i++)
result = comparer(this[i], v);
return result;
}
Array.prototype.max = function(comparer) {
if (this.length === 0) return null;
if (this.length === 1) return this[0];
comparer = (comparer || Math.max);
var result = this[0];
for (var i = 1; i < this.length; i++)
result = comparer(this[i], v);
return result;
}
使用类似的东西:
var minValue = yourArray.min();
var maxValue = yourArray.max();
查看jsbin
:http://jsbin.com/yoyecono/1/edit