首页 > 解决方案 > 有人可以解释这段代码的作用吗?

问题描述

我正试图围绕这段代码片段的作用,但我似乎不明白。

var sentence = ' u i am a girl ';
   
    for(var i = 0; i<sentence.length;i++){
        if (sentence.charAt(i) != ' '){
            sentence = sentence.substring(i, sentence.length);
            console.log(sentence.substring(i, sentence.length));
        
            break
        }
    
    }

标签: javascript

解决方案


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),但由于我不知道代码应该做什么,我只能解释它现在做了什么。


推荐阅读