【发布时间】:2020-10-16 03:47:14
【问题描述】:
目标:输出与单词中的字母相同数量的空白 div。比较两个对象数组,并在适当的位置显示常见的字母。当另一个字母添加到对象数组中时,保留单词显示中的所有先前字母。
问题:比较两个对象并只显示常见的字母。
word: [
{id: 0, val: "w"}
{id: 1, val: "o"}
{id: 2, val: "r"}
{id: 3, val: "d"}
{id: 4, val: "d"}
]
goodAttempts: [
{id: 3, val: "d"}
{id: 4, val: "d"}
]
以下是用于捕获按键并将其分配给状态的代码。 goodAttempts 和 word 的状态(在其他地方捕获并分配)作为 props 传递给组件。
handleKeyDown = (event) => {
let match = [];
let repeat = false;
let letterIndex= [];
let correct = false;
// Validate if the key pressed is recurring in allAttempts
this.state.allAttempts.map((value, index) => {
if( this.state.allAttempts[index] === event.key ) {
return repeat = true;
}
})
// Validate if key pressed matches the word
this.state.word.map((value, index) => {
if( this.state.word[index].val === event.key ) {
letterIndex.push(index);
match.push(this.state.word[index]);
correct = true;
return
}
})
// if repeat is false set allAttempts and repeat. else set repeat to true
if( !repeat ) {
this.setState({
allAttempts: this.state.allAttempts.concat(event.key),
goodAttempts: this.state.goodAttempts.concat(match),
repeat: false,
letterIndex: this.state.letterIndex.concat(letterIndex),
});
} else {
this.setState({
repeat: true,
})
}
}
下面是我想要完成的 sudo 代码
const mapAll = props.word.map((value, index) =>
<div
className="card bg-primary letter-card"
key={value.id}
>
<div className="card-body">
<h5
id={index}
className="card-title letter-card"
>
{where props.goodAttempts === props.word (
{props.goodAttempts} // (the correct letter will display in order)
) : (
BLANK // (no text will display)
)}
</h5>
</div>
</div>
);
我希望将字母留在页面上,直到它被猜到为止,并希望避免直接从脚本中操作 HTML。
Repo
【问题讨论】:
-
看起来很复杂的做法。你不能在单词的字母数组中找到 found:true|false 道具吗? const word = [ { idx:0, letter:'w', found:false }, {idx:1, letter:'o', found:true} ... ]
-
仍然将所有尝试保存在一个数组中以供显示
-
你也可以使用lodash.com/docs/4.17.15#intersectionWith得到匹配猜测的字母交集
标签: javascript arrays reactjs object