我试图创建一个程序,该程序将从使用提示输入的某些文本中删除4000个最常用的单词。这是我做的一个循环,该循环一个接一个地删除您在列表中找到的单词,直到索引到达列表的末尾,并且您删除了所有4000个单词(请参见下面的代码)。问题是什么都没有删除,我的输出与输入相同。我的输入是文本“ The Chungus”,“ The”是列表中的第一个单词。
我检查了每个函数和数据类型是否正确,并且确实删除了循环并用CurrentSpaceIndex和CurrentWordStart替换数字,然后输出正确:“ Chungus”。
var x = "The be and of a in to have to ... "; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..
var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");
var WordToRemove;
var CurrentSpaceIndex = 0;
var CurrentWordStart = 0;
var CurrentChar;
while(CurrentSpaceIndex < 29307){
CurrentChar = x.charAt(CurrentSpaceIndex);
if (CurrentChar = " "){
WordToRemove = x.substring(CurrentWordStart, CurrentSpaceIndex);
ToSimplifyText = ToSimplifyText.replace(WordToRemove, "");
CurrentWordStart = CurrentSpaceIndex + 1;
}
CurrentSpaceIndex = CurrentSpaceIndex + 1;
}
alert(ToSimplifyText);
我希望输出为Chungus
,而不是不变的The Chungus
。
答案 0 :(得分:3)
您正在用非常困难的方式进行操作。您可以按照以下步骤操作:
split()
将两个字符串都转换为单词数组filter()
个来自用户输入的单词出现在单词数组中。join()
并返回结果。
var x = "The be and of a in to have to"; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..
var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");
const removeWords = (str,words) => str.split(' ').filter(x => !words.includes(x)).join(' ');
ToSimplifyText = removeWords(ToSimplifyText,x.split(' '))
alert(ToSimplifyText);
原因是使用Assigment运算符而不是比较运算符。
if (CurrentChar = " ")
应该是
if (CurrentChar === " ")
var x = "The be and of a in to have to"; //It's a list of the 4000 most used words in english. 4000 words with a space between them. The length of the string is 29307 characters, so the last character will have index 29306..
var ToSimplifyText = prompt("Please enter the text you wish to simplify:", "");
var WordToRemove;
var CurrentSpaceIndex = 0;
var CurrentWordStart = 0;
var CurrentChar;
while(CurrentSpaceIndex < x.length){
CurrentChar = x.charAt(CurrentSpaceIndex);
if (CurrentChar === " "){
WordToRemove = x.substring(CurrentWordStart, CurrentSpaceIndex);
console.log(WordToRemove)
ToSimplifyText = ToSimplifyText.replace(WordToRemove, "");
CurrentWordStart = CurrentSpaceIndex + 1;
}
CurrentSpaceIndex = CurrentSpaceIndex + 1;
}
alert(ToSimplifyText);