代码之家  ›  专栏  ›  技术社区  ›  OdunayoO

有人能解释一下这些代码的作用吗?

  •  -4
  • OdunayoO  · 技术社区  · 6 年前

    我正试着把我的脑袋放在这段代码的作用上,但我似乎不明白。

    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
            }
        
        }
    1 回复  |  直到 6 年前
        1
  •  3
  •   Jeppsen    6 年前

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