使用 javascript 数组减少给定的 n 个输入以产生 m 个输出
Use javascript array reduce given n inputs to yield m outputs
我有一系列的点,我想把它们变成一系列的线。
这是我希望代码执行的操作的示例
[p1, p2, p3] -> [line1, line2]
每个循环:
(p1, p2) -> line
(p2, p3) -> line
执行此操作的标准方法是:
const triangle = [[0,0], [0,1], [1,2]]
const lines = []
for (let i = 1; i < triangle.length; ++i) {
const slope = findSlopeFromPoints(...triangle[i - 1], ...triangle[i])
const yIntercept = findYIntercept(...triangle[i], slope)
lines.push({
slope,
yIntercept
})
}
这是我可以使用 Array.prototype.reduce
获得的收盘价。但是感觉更难推理
const initial = {
array: [], // actual returned array we care about
lastPoint: null // "triangle[i - 1]"
}
const linesR = triangle.reduce( (lines, point) => {
if (lines.lastPoint === null)
return {
...lines,
lastPoint: point
}
else {
const slope = findSlopeFromPoints(...lines.lastPoint, ...point)
const yIntercept = findYIntercept(...point, slope)
lines.array.push({
slope,
yIntercept
})
lines.lastPoint = point
return lines
}
}, initial )
简而言之,有没有更好的方法使用reduce将N
个输入组合成N - 1
个输出?
当然可以,使用 currentIndex
参数应用偏移量。您的回调函数接收的参数1 比您使用的参数多:
[{x:0, y:0}, {x:0, y:1}, {x:1, y:2}].reduce((lines, point, currentIndex, source) => {
currentIndex < source.length -1 && lines.push({
from: point,
to: source[currentIndex + 1]
});
return lines;
}, []);
1有关详细信息,请参阅 Array.prototype。<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="nofollow noreferrer">reduce()</a>
。
我有一系列的点,我想把它们变成一系列的线。
这是我希望代码执行的操作的示例
[p1, p2, p3] -> [line1, line2]
每个循环:
(p1, p2) -> line
(p2, p3) -> line
执行此操作的标准方法是:
const triangle = [[0,0], [0,1], [1,2]]
const lines = []
for (let i = 1; i < triangle.length; ++i) {
const slope = findSlopeFromPoints(...triangle[i - 1], ...triangle[i])
const yIntercept = findYIntercept(...triangle[i], slope)
lines.push({
slope,
yIntercept
})
}
这是我可以使用 Array.prototype.reduce
获得的收盘价。但是感觉更难推理
const initial = {
array: [], // actual returned array we care about
lastPoint: null // "triangle[i - 1]"
}
const linesR = triangle.reduce( (lines, point) => {
if (lines.lastPoint === null)
return {
...lines,
lastPoint: point
}
else {
const slope = findSlopeFromPoints(...lines.lastPoint, ...point)
const yIntercept = findYIntercept(...point, slope)
lines.array.push({
slope,
yIntercept
})
lines.lastPoint = point
return lines
}
}, initial )
简而言之,有没有更好的方法使用reduce将N
个输入组合成N - 1
个输出?
当然可以,使用 currentIndex
参数应用偏移量。您的回调函数接收的参数1 比您使用的参数多:
[{x:0, y:0}, {x:0, y:1}, {x:1, y:2}].reduce((lines, point, currentIndex, source) => {
currentIndex < source.length -1 && lines.push({
from: point,
to: source[currentIndex + 1]
});
return lines;
}, []);
1有关详细信息,请参阅 Array.prototype。<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="nofollow noreferrer">reduce()</a>
。