简体   繁体   中英

Trying to reverse string in JavaScript via loop, why doesn't the following code work?

The code is really simple, but I'm not quite sure why it's not working... THe worst part is it isn't even giving me errors!

var str = "Hello";
var lng = str.length - 1

function word() {
    for (var i = lng; i < -1; i--) {
        console.log(str[i]);}
}

word();

The answer is really simple you just have to reverse the symbol in your for loop:

var str = "Hello";
var lng = str.length - 1

function word() {
    for (var i = lng; i > -1; i--) {
        console.log(str[i]);
    }
}

word();

请尝试如下更改for循环。.由于循环反向运行,因此其符号应大于-1而不是小于

   for (var i = lng; i > -1; i--)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM