多维数组中的最小值和最大值

Ben*_*gúz 4 javascript arrays

我的阵列是:

var a = new Array();
a[0] = {x: 10,y: 10};
a[1] = {x: 20,y: 50};
a[2] = {x: 30,y: 20};
a[3] = {x: 10,y: 10};
Run Code Online (Sandbox Code Playgroud)

var min = Math.min.apply(null, a.x)不起作用.一些想法?

the*_*tem 9

你有正确的想法,.apply但你需要传递一组x值.

var xVals = a.map(function(obj) { return obj.x; });
var min = Math.min.apply(null, xVals);
Run Code Online (Sandbox Code Playgroud)

.map()方法创建一个新的数组,包含您在每次迭代中返回的任何内容.

[10, 20, 30, 10]
Run Code Online (Sandbox Code Playgroud)

然后将Array作为第二个参数传递给.apply将分配Array的成员作为单独的参数.所以就好像你这样做了:

Math.min(10, 20, 30, 10) // 10
Run Code Online (Sandbox Code Playgroud)

但是既然你需要.map(),你也可以跳过它Math.min,而只是使用它.reduce.

var min = a.reduce(function(min, obj) { 
                      return obj.x < min ? obj.x : min; 
                   }, Infinity);
Run Code Online (Sandbox Code Playgroud)