javascript - 如何迭代两个数组并生成唯一的 y 坐标

标签 javascript arrays math

上下文:在 Sketch 中,我正在编写一个插件来在 Canvas 上渲染文本,该 Canvas 显示文本的垂直列表及其字体大小 + 粗细组合。

[ 使用 JavaSCript [

问题:我无法弄清楚如何以编程方式正确增加每层的 Y 位置。

假设我有两个数组:

const fontWeights = ['normal', 'bold'];
const fontSizes = ['small', 'medium', 'large'];

我想生成 fontWeight + fontSize 的每个组合的垂直列表,所以它看起来像这样:

smallNormal
smallBold
mediumNormal
mediumBold
largeNormal
largeBold

(或以图形方式表示 see image )

function renderLayers() {
   return fontWeights.map((weight, weightsIndex) => 
       fontSizes.map((size, sizeIndex) => 
           return (
               <TextLayer 
                   fontSize={size} 
                   fontWeight={weight} 
                   yPos={ (weightsIndex + sizeIndex) * 100 } 
               />
}

这有点有效,除了以下情况:

0 + 0 * 100 = 0
0 + 1 * 100 = 100
1 + 0 * 100 = 100 // <-- that should be 200

我真正想做的就是将每次迭代偏移固定量。我确信有一些逻辑/数学方法可以做到这一点,但我被困住了。

帮助将非常感谢!

最佳答案

您可以只保留一个外部变量来存储 yPos:

function renderLayers() {
  let y = 0;
  return fontWeights.map((weight) =>
    fontSizes.map((size) => {
      y = y + 100;
      return <TextLayer fontSize={size} fontWeight={weight} yPos={y} />;
    })
  );
}

map 索引可能不是最适合这项工作的,因为它在 0 和数组长度 - 1 之间交替,所以它确实不是您想要的。您需要 map 外部的一些变量来存储两个迭代组合的“计数”。

我添加了一个新行,但您也可以这样做:

return <TextLayer fontSize={size} fontWeight={weight} yPos={y += 100} />;

关于javascript - 如何迭代两个数组并生成唯一的 y 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61418594/

相关文章:

javascript - 在不影响正常屏幕尺寸的情况下为屏幕尺寸调用样式表

mysql - SQL JSON 数组排序

javascript - 试图在数组中查找 # 个重复项 - 我的函数返回 0?

javascript - 使变量值为正

Javascript 函数未在 Heroku 上加载

javascript - 当页面响应手机/平板电脑时重新排序 div

c - 在 C 中通过引用传递的 3d 数组

java - 定义数字是否为三角数的最快方法

c++ - 如何检查和处理非常接近于零的数字

javascript - 如何更新在 javascript 中使用模板文字的对象值?