代码之家  ›  专栏  ›  技术社区  ›  graham.reeds

最小值/最大值跨越对象数组

  •  6
  • graham.reeds  · 技术社区  · 15 年前

    它已经被杀了,就在这里,就在网上。不过,我想知道是否有办法利用标准的最小/最大功能:

    Array.max = function(array) {
        return Math.max.apply(Math, array);
    };
    
    Array.min = function(array) {
        return Math.min.apply(Math, array);
    };
    

    所以我可以搜索一系列的对象,比如:

    function Vector(x, y, z) { this.x = x; this.y = y; this.z = z; }
    var ArrayVector = [ /* lots of data */ ];
    var min_x = ArrayVector.x.min(); // or
    var max_y = ArrayVector["y"].max();
    

    目前,我必须循环遍历数组并手动比较对象值,然后根据循环的特殊需要来处理每个值。一个更通用的方法会更好(如果稍微慢一点)。

    1 回复  |  直到 15 年前
        1
  •  7
  •   Christian C. Salvadó    15 年前

    你可以对你的 Array.min max 方法要接受属性名,请在以下帮助下提取数组中每个对象的属性 Array.prototype.map ,以及这些提取值的最大值或最小值:

    Array.maxProp = function (array, prop) {
      var values = array.map(function (el) {
        return el[prop];
      });
      return Math.max.apply(Math, values);
    };
    
    var max_x = Array.maxProp(ArrayVector, 'x');
    

    我只想说 数组.prototype.map 方法将在几乎所有现代浏览器上可用,它是 ECMAScript 5th Edition Specification ,但是Internet Explorer没有它,但是您可以很容易地包含一个实现,如 Mozilla Developer Center .