【发布时间】:2021-01-19 06:15:57
【问题描述】:
我正在尝试使文本显示在输入框下方,其中一些字母应替换为下划线。此文本将是用户应输入以获得正确输出的答案。
我希望循环用_ 替换像 e 这样的字母,但它什么也没做。没有错误消息,它只是不替换字母 e。我试图放置一个for 循环,我在其他地方发现了如何替换数组元素中的某些字符,但没有任何效果。
这里是JS代码:
let array = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime']
let arraySecond = ['blue', 'green', 'red', 'orange', 'pink', 'silver', 'purple', 'lime'];
//The other array is the one that shows the element,
//that matches the first array, but with "_", instead of certain letters
document.getElementById('check').addEventListener('click', thisFunction);
function thisFunction() {
let value = document.getElementById('input').value;
if (value == theColor) {
alert(`Congrats you gussed right, its ${value}`)
} else {
alert(`Oof, your guess was incorrect, it\'s ${array[randomizedArray]}`)
}
}
let randomizedArray = Math.floor(Math.random() * array.length);
let theColor = array[randomizedArray];
//One thing the code above is used for is be in the for loop, to replace letters
for (let i = 0; i < theColor.length; i++) {
theColor[i] = theColor[i].replace('e', '_');
}
//This loop that should do the replacing, but it doesn't work
document.getElementById('output').innerHTML = theColor;
【问题讨论】:
-
你能解释一下你想要做什么,例如您想用
_替换字母e(例如)的所有 个实例,还是能够决定替换哪些实例? -
所以程序会选择数组中的某个元素。让我们说蓝色,因为它是数组中的一个元素。然后它将用下划线替换 e,下划线应显示为 blu_。这部分是用第二个数组完成的,第一个是供用户输入的。
-
好的,我明白了,但是如果这个词是“绿色”呢?它应该替换它找到的所有
es 还是只替换一个? -
是的 gr__n 像这样
标签: javascript arrays for-loop replace