JavaScript无法获取最大值或最小值或数组

时间:2014-03-31 01:50:11

标签: javascript arrays max minimum

你好我有一个数组,我似乎无法获得它的最小值和最大值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);

1 个答案:

答案 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();

查看jsbinhttp://jsbin.com/yoyecono/1/edit