我对 JavaScript 很陌生,正在尝试创建一个工具来检查给定文本中的某些单词。现在我正在测试并且可以将结果记录在控制台中,但无法使用innerText显示所有结果。基本上,我希望它显示字符串中存在哪些给定单词,但它只会显示其中一个结果。
这是我的JS代码:
const wordCheckOutput = document.getElementById("word-check-output");
let wordsToCheckFor = ['the', 'a', 'ensure', 'when'];
let sampleString = 'This is a sample string to ensure the code is working.'
function wordCheck() {
let i = [];
for (let i = 0; i < wordsToCheckFor.length; i++) {
let j = [];
for (let j = 0; j < sampleString.split(' ')[j]) {
let results = wordsToCheckFor[i];
console.log(results);
wordCheckOutput.innerText = results;
}
}
}
我相当确定我必须用 [i] 更改结果,但我尝试过的所有方法都不起作用,而且我确定我错过了一些东西。
const wordCheckOutput = document.getElementById("word-check-output");
let wordsToCheckFor = ['the', 'a', 'ensure', 'when'];
let sampleString = 'This is a sample string to ensure the code is working.';
function wordCheck() {
let results = [];
for (let i = 0; i < wordsToCheckFor.length; i++) {
for (let j = 0; j < sampleString.split(' ').length; j++) {
if (sampleString.split(' ')[j] === wordsToCheckFor[i]) {
results.push(wordsToCheckFor[i]);
}
}
}
// Set the inner text after the loop
wordCheckOutput.innerText = results.join(', ');
}
wordCheck();
这应该可以完美满足您的代码要求。