如何在 Javascript 中使用 .map 迭代数组?

How can I iterate an array with .map in Javascript?

我有一个 canvas,大小为 600 x 400 像素。我想每隔 20px 从它的边缘画一条线。我已经将每个点的 x 和 y 坐标创建到 2 个数组中,x 和 y。现在我想 return 每个的值,然后将它插入一个路径以画一条线到 canvas 的中心。 canvas 中心是 300, 200px.

这里我创建了 2 个坐标:

let x = [];
let y = [];
for (let i=0; i<=600; i+=20) {
  x.push(i);
}
for (let i=0; i<=400; i+=20) {
  y.push(i);
}

我已经阅读了有关 .map 的信息,但我无法正确应用它。我该如何解决?

获得这些值后,我想读取每个 x 值并将其与 canvas 上的 y 值配对。

然后我想将这些值插入

ctx.beginPath();
   ctx.moveTo(x, y);
   ctx.lineTo(300, 200);

非常感谢您的反馈!

Array.map 用于迭代集合(例如 [1,2,3,4])。您可以按照以下方式进行操作:

let x = [];
let y = [];
for (let i=0; i<=600; i+=20) {
  x.push(i);
}
for (let i=0; i<=400; i+=20) {
  y.push(i);
}

y.map(coord => console.log(coord))

参考material:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map