分配嵌套地图独特键,javascrpit
我需要分配每个输入自己的ID。
const sep = words.map((word, ind) => {
return (
<div key={ind} className="guess__word">
{word.split("").map((letter, id) => {
if (letter === " ") {
return <SpaceBox key={id} letter={letter} />;
} else {
return <LetterBox key={id} id={id} letter={letter} />;
}
})}
</div>
);
});
我存在的问题是,由于地图的嵌套,ID的值不断重置为0。每个单词的长度都不同,因此如果很难弄清楚是否有一个数学方程是否会帮助我解决这个问题。
作为参考,每个单词的长度是10、3、4和4。
我还需要ID等于单词的长度。因此,我需要ID为0-20。
I need to assign assign each input their own id.
const sep = words.map((word, ind) => {
return (
<div key={ind} className="guess__word">
{word.split("").map((letter, id) => {
if (letter === " ") {
return <SpaceBox key={id} letter={letter} />;
} else {
return <LetterBox key={id} id={id} letter={letter} />;
}
})}
</div>
);
});
The problem that I am having is that due to the map being nested, the value of id keeps reseting back to 0. Each word of words has a different length so if kinda hard to figure out if there is a math equation that would help me solve this.
for reference, the length of each word is 10, 3, 4, and 4.
Also I need the ids to equal up to the length of words. So I would need the ids to be 0-20.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有 - 给定索引 X 和 Y,你可以映射到第 X 个质数的 Y 次方 - 但这在这里太过分了。只需使用字符串连接作为键,例如索引 3 和 4 可以生成
3_4
的键。我建议 不要使用
.split('')< /code>
从字符串中获取字符数组 - 而是调用数组的迭代器,否则当存在奇数字符时偶尔会遇到问题。
如果单词可能发生变化,您可能需要使用稍微不同的键来区分
SpaceBox
字母和LetterBox
字母。如果您必须按从 0 开始的顺序仅使用数组索引,则会更丑陋 - 在外部声明最后使用的数字,然后在循环内使用并递增它。
由于奇数键要求,如果单词是静态的,上述方法只是一个好方法。如果它们可能发生变化,请根据
单词
记住这些框。There is - given indicies X and Y, you can map onto the Xth prime number raised to the Y power - but that's way overkill here. Just use string concatenation, for the key, eg indicies 3 and 4 can produce a key of
3_4
.I'd recommend not using
.split('')
to get a character array from a string - invoke the array's iterator instead, otherwise you'll occasionally run into problems when odd characters are present.If the words may change, you might want to use a slightly different key, to differentiate a
SpaceBox
letter from aLetterBox
letter.If you have to use only array indicies in order starting from 0, it'll be uglier - declare the last used number outside, and use and increment it inside the loop.
Due to the odd key requirement, the above is only a good approach if the words are static. If they may change, memoize the boxes based on the
words
.为了节省数学,您不妨以有意义的方式连接数字
To save math, you might as well just concatenate the numbers in a meaningful way