从JavaScript数组中获取对象值的最大值和最小值

Mar*_*ark 9 javascript performance dojo

从JavaScript对象数组中获取最大值和最小值的最佳方法是什么?

鉴于:

var a = [{x:1,y:0},{x:-1,y:10},{x:12,y:20},{x:61,y:10}];
var minX = Infinity, maxX = -Infinity;
for( var x in a ){
  if( minX > a[x].x )
     minX = a[x].x;
  if( maxX < a[x].x )
     maxX = a[x].x;
}
Run Code Online (Sandbox Code Playgroud)

似乎有点笨拙.是否有更优雅的方式,也许使用道场?

dc5*_*dc5 9

它不会更有效率,只是为了咧嘴笑:

var minX = Math.min.apply(Math, a.map(function(val) { return val.x; }));
var maxX = Math.max.apply(Math, a.map(function(val) { return val.x; }));
Run Code Online (Sandbox Code Playgroud)

或者如果你愿意有三行代码:

var xVals = a.map(function(val) { return val.x; });
var minX  = Math.min.apply(Math, xVals);
var maxX  = Math.max.apply(Math, xVals);
Run Code Online (Sandbox Code Playgroud)


小智 6

使用此示例

var lowest = Number.POSITIVE_INFINITY;
var highest = Number.NEGATIVE_INFINITY;
var tmp;
for (var i=myArray.length-1; i>=0; i--) {
    tmp = myArray[i].Cost;
    if (tmp < lowest) lowest = tmp;
    if (tmp > highest) highest = tmp;
}
console.log(highest, lowest);
Run Code Online (Sandbox Code Playgroud)

  • 你在谈论`tmp`吗?它更有效,因为它避免了重复查找.这个变量绝对需要. (2认同)