【发布时间】:2021-07-25 04:46:58
【问题描述】:
function checkStrings(text, brokenLetters) {
const textArr = text.split(' ');
if (brokenLetters.length === 0) return textArr.length;
const brokenSet = new Set(...brokenLetters.split(' '));
let result = 0;
let check = true;
for (const el of textArr) { //element of array
// check = true;
for (const ch of el) { //char of string(written as el)
if (brokenSet.has(ch))
check = false;
}
if (check) result++;
}
//should return 1, but it's 0 'cause check automatically becomes `false` after the last iteration.
return result;
}
console.log(checkStrings('leet code', 'lt'));
在上面的代码中,如果我没有在第一个循环中添加行 check = true,check 在最后一次迭代后自动将其值更改为“false”,而很明显应该将其更改为 @987654324 @ 仅当if 条件为真时。
有谁知道为什么会这样?
【问题讨论】:
-
check=false曾经被执行过吗? -
不存在自动改变的东西...
-
也许你注释掉了一个重要的行。
>>//check = true;<< -
我认为您应该将集合定义更新为
new Set([...brokenLetters.split(' ')]);或只是new Set(brokenLetters.split(' '));通过控制台日志检查brokenSet是否具有预期值。
标签: javascript string loops variables