I have here two snippets of code, one using traditional for loop and the other using for...of loop.
export function spinWords(words: string): string {
const singleWords: string[] = words.split(' ');
for (let i = 0; i < singleWords.length; i ) {
if (singleWords[i].length >= 5) {
singleWords[i] = singleWords[i].split('').reverse().join('');
}
}
return singleWords.join(' ');
}
export function spinWords(words: string): string {
const singleWords: string[] = words.split(' ');
for (let word of singleWords) {
if (word.length >= 5) {
word = word.split('').reverse().join('');
}
}
return singleWords.join(' ');
}
Why is that in the former snippet, my function spinWords
was able to reverse any word with a length >5, whereas in the latter, the array singleWords
remain unchanged even the word
elements (with length>=5) were reversed?
CodePudding user response:
With the for loop you are manipulating the entry in the array, while with the for of loop you get a new variable word
(which is correctly reversed) but only for the variable itself. You are not changing anything in the array. if you do:
export function spinWords(words: string): string {
const singleWords: string[] = words.split(' ');
for (let word of singleWords) {
if (word.length >= 5) {
const idx = singleWords.indexOf(word);
singleWords[idx] = word.split('').reverse().join('');
}
}
return singleWords.join(' ');
}
It will work the same as the for loop.
NOTE: while this works, its better to use a for loop (or using the built in forEach, that can access the index as well) for this use case here.