【问题标题】:How can I iterate an array with .map in Javascript?如何在 Javascript 中使用 .map 迭代数组?
【发布时间】:2021-03-07 20:07:45
【问题描述】:

我有一个画布,大小为 600 x 400 像素。我想每隔 20px 从它的边缘画一条线。我已将每个点的 x 和 y 坐标创建为 2 个数组 x 和 y。现在我想返回每个的值,然后将其插入到路径中以画一条线到画布的中心。画布中心为 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 值并将其与画布上的 y 值配对。

然后我想将这些值插入

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

非常感谢您的反馈!

【问题讨论】:

    标签: array.prototype.map


    【解决方案1】:

    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))
    

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

    【讨论】:

    • 请将代码作为文本,而不是屏幕截图。
    猜你喜欢
    • 2018-08-21
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-19
    • 2011-01-31
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    相关资源
    最近更新 更多