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

伪代码示例:

let array = [100, 0, 50]

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

当前回答

下面的脚本在ndoejs中为我工作:

 var numbers = [1, 2, 3, 4];
 console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4

其他回答

当意图是调用带有参数值列表的变进函数时,.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将工作没有问题。

为了防止“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

使用展开运算符(ES6)

Math.max(...array)  // The same with "min" => Math.min(...array)

Const数组= [10,2,33,4,5]; console.log ( Math.max数组(…) )

创建一个简单的对象

var myArray = new Array();

myArray = [10,12,14,100];

var getMaxHeight = {
     hight : function( array ){ return Math.max.apply( Math, array );
}

getMaxHeight.hight(myArray);