我正在使用一个公式来存档平行四边形的面积
理论乘积的数学公式:((x1 * y2 - y1 * x2) + (x2 * y3 - y2 * x3) + (x3 * y4 - y3 * x4) + (x4 * y1 - y4 * x1)) / 2
问题是:我正在"手工"完成:
(points[0].x * points[1].y - points[0].y * points[1].x) +
(points[1].x * points[2].y - points[1].y * points[2].x) +
(points[2].x * points[3].y - points[2].y * points[3].x) +
(points[3].x * points[0].y - points[3].y * points[0].x)) / 2
有没有办法使用类似的东西来存档相同的结果reduce
,试图避免经典的for
循环?
您可以使用模数访问下一个(或环绕(点,同时reduce
:
const vProd = points.reduce((sum, point, i, arr) => {
const { x, y } = arr[(i + 1) % arr.length];
return sum
+ point.x * y
- point.y * x
}, 0);
不确定它是否更好; 原始 4 行的功能虽然冗长,但非常清楚