TransWikia.com

How can I make a for loop increment a variable based on the value of a string character?

Stack Overflow Asked by David Martin on December 11, 2021

I feel like it’s something super obvious, but I can’t figure out what’s going on here. When I console.log(countA) it returns 2. I know I’m gonna kick myself once I see what’s wrong with it.

let n = 10
let s = 'aba'
let x = n / s.length
let countA = 0  
let newStr = s.repeat(x)

for (i = 0; i < newStr.length; i++) {
    if (s.charAt(i) == 'a') {
        countA++
    }
}

When I console.log(newStr) I get abaabaaba

I’ve tried changing the loop to:

for (i = 0; i < newStr.length; i++) {
    console.log(newStr.charAt(i))
}

Which displays all 9 letters. What am I doing wrong?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP