我有这个包含对象的数组:
var pts = [
{ "X": 52.67528921580262, "Y": 8.373513221740723 },
{ "X": 52.6759657545252, "Y": 8.374114036560059 },
{ "X": 52.682574466310314, "Y": 8.37256908416748 },
{ "X": 52.68356308524067, "Y": 8.373942375183105 },
{ "X": 52.68293869694087, "Y": 8.375487327575684 },
{ "X": 52.67685044320001, "Y": 8.376259803771973 },
{ "X": 52.6756535071859, "Y": 8.379607200622559 },
{ "X": 52.676017795531436, "Y": 8.382096290588379 },
{ "X": 52.68101344348877, "Y": 8.380722999572754 },
{ "X": 52.68351105322329, "Y": 8.383641242980957 },
{ "X": 52.68, "Y": 8.389 }
];
如何找到最小值,最大值为X和最小值,最大值为Y?
答案 0 :(得分:6)
你可以调用Math.min
和Math.max
,传入一个只包含相关值的映射数组,如下所示:
function endProp( mathFunc, array, property ) {
return Math[ mathFunc ].apply(array, array.map(function ( item ) {
return item[ property ];
}));
}
var maxY = endProp( "max", pts, "Y" ), // 8.389
minY = endProp( "min", pts, "Y" ); // 8.37256908416748
答案 1 :(得分:1)
对数组进行排序可能最简单。
array.sort(function minXToMaxX(a,b){
return a.x - b.x;
});
最低x
值为array[0]
。最高x
值为array[array.length - 1]
;
答案 2 :(得分:1)
此代码工作正常。请参阅snippt了解演示。
var pts = [{
"X": 52.67528921580262,
"Y": 8.373513221740723
}, {
"X": 52.6759657545252,
"Y": 8.374114036560059
}, {
"X": 52.682574466310314,
"Y": 8.37256908416748
}, {
"X": 52.68356308524067,
"Y": 8.373942375183105
}, {
"X": 52.68293869694087,
"Y": 8.375487327575684
}, {
"X": 52.67685044320001,
"Y": 8.376259803771973
}, {
"X": 52.6756535071859,
"Y": 8.379607200622559
}, {
"X": 52.676017795531436,
"Y": 8.382096290588379
}, {
"X": 52.68101344348877,
"Y": 8.380722999572754
}, {
"X": 52.68351105322329,
"Y": 8.383641242980957
}, {
"X": 52.68,
"Y": 8.389
}];
var xobj = [];
var yobj = [];
var len = pts.length;
for (var i = 0; i < len; i++) {
xobj.push(parseFloat(pts[i].X));
yobj.push(parseFloat(pts[i].Y));
}
//height x value
var value = xobj[0];
for (var n = 1; n < xobj.length; n++) {
if (xobj[n] > value) {
value = xobj[n];
}
}
//lowest x value
var valuel = xobj[0];
for (var n = 1; n < xobj.length; n++) {
if (xobj[n] < valuel) {
valuel = xobj[n];
}
}
//height y value
var valueY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
if (yobj[n] > valueY) {
valueY = yobj[n];
}
}
//lowest x value
var valuelY = yobj[0];
for (var n = 1; n < yobj.length; n++) {
if (yobj[n] < valuelY) {
valuelY = yobj[n];
}
}
document.getElementById("demo").innerHTML = valuel
document.getElementById("demo1").innerHTML = value
document.getElementById("demo2").innerHTML = valuelY
document.getElementById("demo3").innerHTML = valueY
Minx:
<p id="demo"></p>
MaxX:
<p id="demo1"></p>
Miny:
<p id="demo2"></p>
MaxY:
<p id="demo3"></p>