如何使用javascript在数组中找到最大的顶部和左侧值?
var array =[{type: "rect", originX: "left", originY: "top", left: 482.01, top: 76, …}
1
:
{type: "rect", originX: "left", originY: "top", left: 584.01, top: 177.01, …}
2
:
{type: "rect", originX: "left", originY: "top", left: 786, top: 157.01, …}
3
:
{type: "path-group", originX: "left", originY: "top", left: 399, top: 382, …}
4
:
{type: "path-group", originX: "left", originY: "top", left: 623.01, top: 378.01, …}
5
:
{type: "circle", originX: "left", originY: "top", left: 103, top: 173, …}
答案 0 :(得分:0)
我认为你想要像...这样的东西。
var array = [ {left: 482.01, top: 76}, {left: 584.01, top: 177.01}, {left: 786, top: 157.01}, {left: 399, top: 382} ];
var maxLeft = 0, maxTop = 0;
array.forEach(e => {
e.left > maxLeft && (maxLeft = e.left);
e.top > maxTop && (maxTop = e.top);
});
console.log(maxLeft, maxTop);

ES6的清洁方式:
var array = [ {left: 482.01, top: 76}, {left: 584.01, top: 177.01}, {left: 786, top: 157.01}, {left: 399, top: 382} ];
let { maxLeft, maxTop } = maxLeftAndMaxTop(array);
console.log("maxLeft: ", maxLeft, "maxTop: ", maxTop);
function maxLeftAndMaxTop(arr, maxLeft = 0, maxTop = 0) {
arr.forEach(e => {
e.left > maxLeft && (maxLeft = e.left);
e.top > maxTop && (maxTop = e.top);
});
return { maxLeft, maxTop };
}
console.log(maxLeft, maxTop);

答案 1 :(得分:-1)
如果您只想返回最高值,可以减少数组并返回left
或top
的最高值。例如:
array = [{type: "rect", originX: "left", originY: "top", left: 482.01, top: 76},
{type: "rect", originX: "left", originY: "top", left: 584.01, top: 177.01},
{type: "rect", originX: "left", originY: "top", left: 786, top: 157.01},
{type: "path-group", originX: "left", originY: "top", left: 399, top: 382},
{type: "path-group", originX: "left", originY: "top", left: 623.01, top: 378.01},
{type: "circle", originX: "left", originY: "top", left: 103, top: 173}];
// Get left
array.reduce((result, item) => item.left > result ? item.left : result, 0); // => 786
// Get top
array.reduce((result, item) => item.top > result ? item.top : result, 0); // => 382
如果您不想使用ES6语法,则可以使用普通函数:
array.reduce(function(result, item) {
return item.left > result ? item.left : result
}, 0);