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

伪代码示例:

let array = [100, 0, 50]

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

当前回答

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

其他回答

let arr = [2,5,3,5,6,7,1];

let max = Math.max(...arr); // 7
let min = Math.min(...arr); // 1

使用Math.max()或Math.min()

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

下面的函数使用function .prototype.apply()来查找数值数组中的最大元素。getMaxOfArray([1,2,3])等价于Math。max(1,2,3),但是您可以在任何大小的编程构造数组上使用getMaxOfArray()。

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

或者使用新的展开运算符,获得数组的最大值变得容易得多。

var arr = [1, 2, 3];
var max = Math.max(...arr); // 3
var min = Math.min(...arr); // 1

下面的代码为我工作:

var valueList = [10,4,17,9,3];
var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });
var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });

下面是一种从对象数组中获取最大值的方法。创建一个副本(使用切片),然后按降序对副本排序并抓取第一项。

var myArray = [
    {"ID": 1, "Cost": 200},
    {"ID": 2, "Cost": 1000},
    {"ID": 3, "Cost": 50},
    {"ID": 4, "Cost": 500}
]

maxsort = myArray.slice(0).sort(function(a, b) { return b.ID - a.ID })[0].ID; 

这里有很多不错的答案,下面是一个typescript版本,可以处理一些值未定义的列表。

如何使用:

const testDates = [
  undefined,
  new Date('July 30, 1986'),
  new Date('July 31, 1986'),
  new Date('August 1, 1986'),
]
const max: Date|undefined = arrayMax(testDates); // Fri Aug 01 1986
const min: Date|undefined = arrayMin(testDates); // Min: Wed Jul 30 1986
const test: Date = arrayMin(testDates); // Static type error
const anotherTest: undefined = arrayMin(testDates); // Static type error

定义(notEmpty定义来自这篇文章):

function arrayMax<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a >= b ? a : b), nonEmptyValues[0]);
}

function arrayMin<T>(values?: (T | null | undefined)[]): T | undefined {
    const nonEmptyValues = filterEmpty(values);
    if (nonEmptyValues.length === 0) {
        return undefined;
    }
    return nonEmptyValues.reduce((a, b) => (a <= b ? a : b), nonEmptyValues[0]);
}

function filterEmpty<T>(values?: (T | null | undefined)[] | null): T[] {
    return values?.filter(notEmpty) ?? [];
}

function notEmpty<T>(value: T | null | undefined): value is T {
    if (value === null || value === undefined) return false;
    const testDummy: T = value;
    return true;
}

我没有使用数学。max函数,正如文档中建议的那样,因为这样我就可以将这个函数与任何可比对象一起使用(如果你知道如何键入它,请告诉我,这样我就可以更好地定义T)。