Home > Back-end >  why doesn't this work? it's a simple console log inside a loop
why doesn't this work? it's a simple console log inside a loop

Time:06-06

var line = "Stands so high   ";

let position = -1;
for (; line[position] == " ";) {
  position--;
  console.log(position);
}

the output gives nothing. why is it this way? I want it to console.log the value position. I have used both node and the chrome developer tools console. Doesn't work on either one.

CodePudding user response:

While in some other languages, negative string indexes can be used to count from the end backwards, this is not the case in JavaScript.

Newer JS engines support the at method for that:

var line="Stands so high   ";

let position=-1;
for(;line.at(position)==" ";) {
    position--;
    console.log(position);
}

CodePudding user response:

var line = "Stands so high";

for (let position = 0; position < line.length; position  ) {
  console.log(position);
}

  • Related