JavaScript 中字符串中非唯一字符的数量
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/31 23:08:17
我们需要编写一个 JavaScript 函数,该函数接受一个字符串并返回字符串中冗余字符的数量。
例如:如果字符串为 −
const str = 'abcde'
则输出应为 0。
如果字符串为 −
const str = 'aaacbfsc';
则输出应为 3。
示例
其代码为 −
const str = 'aaacbfsc';
const countRedundant = str => {
let count = 0;
for(let i = 0; i < str.length; i++){
if(i === str.lastIndexOf(str[i])){
continue;
};
count++;
};
return count;
};
console.log(countRedundant(str));
输出
控制台中的输出将是 −
3
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

