Home > Back-end >  why For loop not showing the right index number. a = 2 (should be 7) and l = 3 (should be 9) what i
why For loop not showing the right index number. a = 2 (should be 7) and l = 3 (should be 9) what i

Time:10-13

let input = 'whale talk'
const vowels = ['a','e','i','o','u']

let resultArray = []

for (item of input.replace(' ','')){

    console.log(item   ' = '   input.indexOf(item))

}

result

w = 0
h = 1
a = 2
l = 3
e = 4
t = 6
a = 2
l = 3
k = 9

CodePudding user response:

for - of iterates with the element's value. To deal with the element's index for - in can be used.

let input = 'whale talk';
for (const index in input) {
    const item = input[index];
    if(item != " ") {
        console.log(item   ' = '   index)
    }
}

Below is the result with correct running index of each element

w = 0
​h = 1
​a = 2
​l = 3
​e = 4
​t = 6
​a = 7
​l = 8
​k = 9

CodePudding user response:

As Wazeed said, indexOf always finds the first occurence of the searched value.

Since strings do have an index and a length property you can use a simple for loop:

let input = 'whale talk'
const strippedInput = input.replace(' ', '')

for (i = 0; i < strippedInput.length; i  ) {
  console.log(strippedInput[i])
}

If your input contains more than one space, you can use replaceAll instead of replace (or look into regular expressions for even more advanced stuff).

  • Related