document.onkeyup = function(event){
if(answer.indexOf(event.key) > -1){
console.log(answer.indexOf(event.key));
console.log(typeof event.key);
//cover[answer.indexOf(event.key)] = event.key; this doesnt work
//cover.replace(cover[answer.indexOf(event.key)],event.key); this doesnt
work
console.log(cover);
}
}
我有一个看起来像这样的字符串:" -------"这代表了相同长度的隐藏答案。当用户点击答案字符串中的键时,我希望该字符出现在同一索引处的隐藏字符串中。
答案 0 :(得分:1)
var answer = 'correcthorsebatterystaple';
// generate an array of '-' the same length as the answer
var cover = answer.split('').map(x => '-');
document.getElementById('c').innerText = cover.join('');
document.onkeyup = function(e) {
var key = e.key;
for (var i = 0; i < cover.length; i++) {
// for each instance of the pressed letter in the answer, replace the corresponding dash(es) in cover
if (answer[i] === key) cover[i] = key;
}
document.getElementById('c').innerText = cover.join('');
}
&#13;
<span id="c" style="font-family:monospace"></span>
&#13;