我的代码中遗漏了什么吗?它似乎只抓取第一个字母,而 while 循环不会进入下一个单词。那么我可能会错过什么?
function acr(s){
var words, acronym, nextWord;
words = s.split();
acronym= "";
index = 0
while (index<words.length) {
nextWord = words[index];
acronym = acronym + nextWord.charAt(0);
index = index + 1 ;
}
return acronym
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您只关心 IE9+,那么答案可以缩短:
function acronym(text) {
return text
.split(/\s/)
.reduce(function(accumulator, word) {
return accumulator + word.charAt(0);
}, '');
}
console.log(acronym('three letter acronym'));Run Code Online (Sandbox Code Playgroud)
如果你可以使用箭头函数,那么它可以更短:
function acronym(text) {
return text
.split(/\s/)
.reduce((accumulator, word) => accumulator + word.charAt(0), '');
}
console.log(acronym('three letter acronym'));Run Code Online (Sandbox Code Playgroud)
将分隔符添加到split:
function acr(s){
var words, acronym, nextWord;
words = s.split(' ');
acronym= "";
index = 0
while (index<words.length) {
nextWord = words[index];
acronym = acronym + nextWord.charAt(0);
index = index + 1 ;
}
return acronym
}
Run Code Online (Sandbox Code Playgroud)
修改了上面的内容,使其更具演示性,也更具互动性:JS Fiddle demo。
因为没有提供分隔符,所以字符串保持未分割状态;因此while操作正确(等于words.length)1,因此仅返回字符串的第一个字母:
[Separator] 指定用于分隔字符串的字符。分隔符被视为字符串或正则表达式。如果省略分隔符,则返回的数组包含一个由整个字符串组成的元素。
参考:
| 归档时间: |
|
| 查看次数: |
5639 次 |
| 最近记录: |