想象一下需要点来绘制正弦波:
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);
答案 0 :(得分:2)
您可以使用Array.from
生成数组:
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;
提供给Array.from
的第二个参数是一个可选的map
函数,其行为与Array.prototype.map
完全相同。