我怎样才能轻松地获得一个JavaScript数组的最小或最大元素?

伪代码示例:

let array = [100, 0, 50]

array.min() //=> 0
array.max() //=> 100

当前回答

如果你有一个复杂的对象,你可以使用排序....例如:如果我想获得包含MAX/MIN值低于objs的项目。

var objs= [
{name:"Apple",value:3},
{name:"Love",value:32},
{name:"Cheese",value:1},
{name:"Pork",value:77},
{name:"Xmas",value:99}        
];

我会做一个排序:

objs.sort(function(a, b){return a.value-b.value});

然后: objs[0]是最小值,objs[objs. obs]length-1]是最大值。

其他回答

除了使用数学函数max和min之外,另一个要使用的函数是sort()的内置函数:开始吧

const nums = [12, 67, 58, 30].sort((x, y) => 
x -  y)
let min_val = nums[0]
let max_val = nums[nums.length -1]
array.sort((a, b) => b - a)[0];

给出数字数组中的最大值。

array.sort((a, b) => a - b)[0];

给出一组数字中的最小值。

Let array = [0,20,45,85,41,5,7,85,90,111]; 令maximum = array。排序((a, b) => b - a)[0]; 令minimum = array。排序((a, b) => a - b)[0]; console.log(最小值,最大值)

很简单,真的。

var arr = [10,20,30,40];
arr.max = function() { return  Math.max.apply(Math, this); }; //attach max funct
arr.min = function() { return  Math.min.apply(Math, this); }; //attach min funct

alert("min: " + arr.min() + " max: " + arr.max());

其他人已经给出了一些增强Array.prototype的解决方案。我想在这个回答中澄清它是否应该是Math.min。apply(Math, array)或Math.min。应用(null,数组)。那么应该使用什么上下文,数学还是空?

当将null作为上下文传递给apply时,上下文将默认为全局对象(浏览器中的窗口对象)。将Math对象作为上下文传递是正确的解决方案,但传递null也不会造成伤害。这里有一个例子,当装饰Math时,null可能会引起麻烦。max函数:

// decorate Math.max
(function (oldMax) {
    Math.max = function () {
        this.foo(); // call Math.foo, or at least that's what we want

        return oldMax.apply(this, arguments);
    };
})(Math.max);

Math.foo = function () {
    print("foo");
};

Array.prototype.max = function() {
  return Math.max.apply(null, this); // <-- passing null as the context
};

var max = [1, 2, 3].max();

print(max);

上面的代码将抛出异常,因为。Foo将被计算为window。Foo,没有定义。如果我们用Math替换null,事情就会像预期的那样工作,字符串“foo”将被打印到屏幕上(我使用Mozilla Rhino进行测试)。

你几乎可以假设没有人授予过数学勋章。所以,传递null将工作没有问题。

下面是一个简单的JS方法。

function getMinArrayVal(seq){
    var minVal = seq[0];
    for(var i = 0; i<seq.length-1; i++){
        if(minVal < seq[i+1]){
        continue;
        } else {
        minVal = seq[i+1];
        }
    }
    return minVal;
}