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

伪代码示例:

let array = [100, 0, 50]

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

当前回答

很简单,真的。

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

其他回答

在这个时代(2022年),从数组中获得min + max的最有效方法是通过reduce在一次迭代中完成。

在JavaScript中:

const arr = [3, 0, -2, 5, 9, 4];

const i = arr.reduce((p, c) => {
    p.min = c < p.min ? c : p.min ?? c;
    p.max = c > p.max ? c : p.max ?? c;
    return p;
}, {min: undefined, max: undefined});

console.log(i); //=> { min: -2, max: 9 }

当输入没有数据时,它将输出{min: undefined, max: undefined}。

在TypeScript中,你只需要添加类型强制转换,所以返回类型被推断为{min: number, max: number},而不是{min: any, max: any}:

const arr = [3, 0, -2, 5, 9, 4];

const i = arr.reduce((p, c) => {
    p.min = c < p.min ? c : p.min ?? c;
    p.max = c > p.max ? c : p.max ?? c;
    return p;
}, {min: undefined as number, max: undefined as number});
//=> {min: number, max: number}

console.log(i); //=> { min: -2, max: 9 }

更新

在kiran goud注释之后,这里有一个使用数组而不是对象的替代方法:

const i = arr.reduce((p, c) => {
    p[0] = c < p[0] ? c : p[0] ?? c;
    p[1] = c > p[1] ? c : p[1] ?? c;
    return p;
}, [undefined, undefined]);

console.log(i); //=> [-2, 9]

为了防止“max”和“min”被列在“for…”在“循环:

Object.defineProperty(Array.prototype, "max", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.max.apply(null, this);
    }
});
Object.defineProperty(Array.prototype, "min", {
    enumerable: false,
    configurable: false,
    writable: false,    
    value: function() {
        return Math.min.apply(null, this);
    }
});

用法:

var x = [10,23,44,21,5];
x.max(); //44
x.min(); //5

遍历,在执行过程中保持跟踪。

var min = null;
var max = null;
for (var i = 0, len = arr.length; i < len; ++i)
{
    var elem = arr[i];
    if (min === null || min > elem) min = elem;
    if (max === null || max < elem) max = elem;
}
alert( "min = " + min + ", max = " + max );

如果数组中没有元素,这将使min/max为空。如果数组中有任何元素,将在一次传递中设置最小值和最大值。

您还可以使用上述方法使用range方法扩展Array,以允许重用并提高可读性。在http://jsfiddle.net/9C9fU/上看到一个工作的小提琴

Array.prototype.range = function() {

    var min = null,
        max = null,
        i, len;

    for (i = 0, len = this.length; i < len; ++i)
    {
        var elem = this[i];
        if (min === null || min > elem) min = elem;
        if (max === null || max < elem) max = elem;
    }

    return { min: min, max: max }
};

用作

var arr = [3, 9, 22, -7, 44, 18, 7, 9, 15];

var range = arr.range();

console.log(range.min);
console.log(range.max);

当意图是调用带有参数值列表的变进函数时,.apply经常被使用。

的数学。Max ([value1[,value2,…]])函数返回零个或多个数字中最大的一个。

Math.max(10, 20); // 20
Math.max(-10, -20); // -10
Math.max(-10, 20); // 20

Math.max()方法不允许传入数组。如果你有一个需要获取最大值的值列表,你通常会使用function .prototype.apply()调用这个函数,例如:

Math.max.apply(null, [10, 20]); // 20
Math.max.apply(null, [-10, -20]); // -10
Math.max.apply(null, [-10, 20]); // 20

然而,从ECMAScript 6开始,你可以使用扩展操作符:

展开运算符允许在需要多个参数(用于函数调用)或多个元素(用于数组字面量)的地方展开表达式。

使用展开运算符,上面的代码可以重写为:

Math.max(...[10, 20]); // 20
Math.max(...[-10, -20]); // -10
Math.max(...[-10, 20]); // 20

当使用可变值操作符调用函数时,您甚至可以添加额外的值,例如:

Math.max(...[10, 20], 50); // 50
Math.max(...[-10, -20], 50); // 50

奖金:

展开运算符使您能够在ES5中需要返回到命令式代码(使用push、splice等组合)的情况下使用数组文字语法创建新数组。

let foo = ['b', 'c'];
let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']

其他人已经给出了一些增强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将工作没有问题。