有人可以解释此代码的作用吗?

时间:2018-07-11 07:32:15

标签: javascript

我正在努力把这段代码片段做些事情,但我似乎没有得到。

1 个答案:

答案 0 :(得分:3)

var sentence = ' u i am a girl ';
    
    // Loop through the sentence string
    for (var i = 0; i < sentence.length; i++) {
        
        // If the current character isn't one space
        if (sentence.charAt(i) != ' ') {
            
            // Remove all the characters up until the first none-space character
            sentence = sentence.substring(i, sentence.length);
            // Will give us 'u i am a girl '
            
            // Double the amount of removed characters in the remaining string before we log it
            console.log(sentence.substring(i, sentence.length));
            // Since we removed 1 character in the substring before,
            // we will now remove 1 more character 
            // Result will be ' i am a girl '

            // Exit the for loop
            break;
        }

    }

感觉第二个子字符串是多余的,应该 console.log(sentence),但是由于我不知道代码应该做什么,所以我现在只能解释它的作用。