I am a very beginner JS "developer" (student) and I have run into a question I haven't been able to solve: why does the value of the repeated letters in my 'helperHash' increase when I am not using an else statement and why this same value DOESN't increase if I use an else statement? My code runs as expected but I am having problems understanding the logic behind this issue...
The code is supposed to return an array with the letters that have 1 or more repetitions in the given str.
function nonUniqueLetters(str){
var strToChars = str.split('');
var finalArr = [];
var helperHash = {};
for (let i = 0; i < strToChars.length; i += 1){
let char = str[i];
if (!helperHash[char]){
helperHash[char] = 0;
}
helperHash[char] += 1; //HERE! why doesn't this work if inside an else?
}
for (var key in helperHash){
if (helperHash[key] > 1){
finalArr.push(key);
}
}
return finalArr;
}
Aucun commentaire:
Enregistrer un commentaire