我有个坏词,里面有非法信件。我有一个法律信件的列表(可以是多个字符长)。下面的嵌套循环迭代单词和合法字母中的字符,用null替换任何非法字母。
为了既保留合法信件,又代替非法信件,重要的是所有的法律信函都要通过。一旦循环结束,非法的替换就会发生。
// acceptable letters:
const legalLetters = ["ND", "CH", "S"]
// bad, evil word containing unacceptable letters:
let word = "SANDWICH"
const filteredLetters = []
while (word.length > 0) {
for (const letter of legalLetters) {
if (word.startsWith(letter)) {
// remove that many letters from the start of the word
word = word.slice(letter.length)
filteredLetters.push(letter)
// break back to the while loop to re-scan the truncated word
break
}
} else {
// this is the part I'm having trouble with
// if the word does not start with an acceptable letter, remove that letter
word = word.slice(1)
filteredLetters.push(null)
}
// some filteredLetter was added and the length of the word has been reduced
// repeat until the word is all gone
}
console.log(filteredLetters) // should be ["S", null, "ND", null, null, "CH"]在上面的示例中,我使用了Python的for ... else构造,它只在else块中没有break时才执行for块中的代码。这样的语法在Javascript中是不存在的(因此上面的片段是无稽之谈)。
我将如何在Javascript中创建这种“默认行为”?
洛达什公司就我的目的而言,答案是可以的,这很可能是XY问题,所以我欢迎任何重组建议。
相关问题:其他循环在Javascript中吗?
此问题的答案建议设置布尔标志或拆分到标签。如果可能的话,我更倾向于避免这些方法--标记方法感觉很混乱,创建了一个不必要的变量,而标签方法则是只是感觉不太好。
发布于 2020-07-08 17:59:05
我希望这能帮到你。
// acceptable letters:
const legalLetters = ["ND", "CH", "S"]
// bad, evil word containing unacceptable letters:
let word = "SANDWICH"
const filteredLetters = []
while (word.length > 0) {
let pushedItem = null;
for (const letter of legalLetters) {
if (word.startsWith(letter)) {
pushedItem = letter;
break
}
}
word = word.slice(pushedItem ? pushedItem.length : 1)
filteredLetters.push(pushedItem)
}
console.log(filteredLetters)
https://stackoverflow.com/questions/62800188
复制相似问题