javascript - 有人可以解释这段代码的作用吗?
问题描述
我正试图围绕这段代码片段的作用,但我似乎不明白。
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
}
}
解决方案
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)
,但由于我不知道代码应该做什么,我只能解释它现在做了什么。
推荐阅读
- php - 创建反转单词但保留任何空格的函数?
- typescript - 在打字稿的接口中使用枚举值作为类型
- javascript - 将函数添加到 DOM 元素中
- android - 如何将普通 Android 应用程序转换为 Android Auto 应用程序?
- javascript - 如何获取输入值,然后针对 0 索引处的所有数组对象值进行检查
- sql - 如何通过引用sql中的日期和状态进行排名
- r - 如何从 R 中的 multiples facet_grid 的子集中添加点?
- python-3.x - grouby 对象的形状及其转换后的数据框对象
- python - 如何在python中使用pynput输出每次按下空格键之间的时间
- php - 使用由 for 或 foreach 循环完成的关联数组创建 wordpress 更新查询