shivansh sharma
shivansh sharma

Reputation: 1

Using "for in" over a string to find a character but then not able to use the variable to reference another value

Still learning JS and confused over this

The below code gives out undefined as output when it should be "v" - am I missing something or using for-in over a string is the issue

let s="iydafgvb";
var i = 0
for(i in s){
    if(s.charAt(i)=="a"){
        break;
    }
} 
console.log(s.charAt(i));

Expecting "v" but getting "undefined"

Upvotes: 0

Views: 40

Answers (1)

TheLazyCat
TheLazyCat

Reputation: 11

You cant use for(char in string) in js and use char as the actual character. To iterate over a string you should use for of: for(let char of string). You can now access the characters with the char variable:

let text = "hello"

for(let char of text){
  console.log(char);
}

/* this will output

h
e
l
l
o
*/

You can also convert the string to an array: let array = Array.from(text). Now you can use array like a regular array.

Upvotes: 1

Related Questions