上下文:在 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/