JavaScript
如果字符串中存在重复字符,该函数将给出输出“true”,
否则它将输出“false”
function repeatChar(str) {
for (let char of str.toLowerCase()) {
if (str.indexOf(char) !== str.lastIndexOf(char)) {
return true;
}
}
return false;
}
console.log(repeatChar('aA')); //expected output "true" but here output is "false"... Why??
最佳答案
您正在搜索原始字符串中的小写字符,该字符尚未转换为全部小写。
您应该在循环之前将 str
替换为其小写版本。
function repeatChar(str) {
str = str.toLowerCase();
for (let char of str) {
if (str.indexOf(char) !== str.lastIndexOf(char)) {
return true;
}
}
return false;
}
console.log(repeatChar('aA')); //expected output "true" but here output is "false"... Why??
关于javascript - 为什么这个 'repeated character"查找功能不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62965030/