使用像map或reduce这样的数组运算符从角度0到2π获得n个点?

时间:2018-05-15 02:26:03

标签: javascript pi

想象一下需要点来绘制正弦波:

let points = [];
for(var angle = 0; angle < Math.PI * 2; angle += .01) {
  points.push(Math.sin(angle));
}

console.log(points);

现在想象一下,我们想要控制点数,但仍然可以获得2π的完整旋转:

const pointsArr = new Array(10000).fill().map((i) => {
  // how to convert above loop 
});

console.log(pointsArr);

1 个答案:

答案 0 :(得分:2)

您可以使用Array.from生成数组:

&#13;
&#13;
function makePoints(numPoints) {
  const diffBetweenPoints = (Math.PI * 2) / (numPoints - 1);
  return Array.from({ length: numPoints }, (_, i) => Math.sin(i * diffBetweenPoints));
}
console.log(makePoints(5));
&#13;
&#13;
&#13;

提供给Array.from的第二个参数是一个可选的map函数,其行为与Array.prototype.map完全相同。