javascript中的首字母缩略词生成器。它只抓取第一个单词的第一个字母,而不抓取其他单词的第一个字母
我的代码中遗漏了什么吗?它似乎只抓住了第一个字母,而while循环并没有进入下一个单词。那么我会错过什么呢javascript中的首字母缩略词生成器。它只抓取第一个单词的第一个字母,而不抓取其他单词的第一个字母,javascript,Javascript,我的代码中遗漏了什么吗?它似乎只抓住了第一个字母,而while循环并没有进入下一个单词。那么我会错过什么呢 function acr(s){ var words, acronym, nextWord; words = s.split(); acronym= ""; index = 0 while (index<words.length) { nextWord = words[index]; acron
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
}
功能acr(s){
变量词,首字母缩略词,nextWord;
words=s.split();
首字母缩略词=”;
索引=0
而(索引将分隔符添加到拆分中
:
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
}
功能acr(s){
变量词,首字母缩略词,nextWord;
文字=s.split(“”);
首字母缩略词=”;
索引=0
而(index您忘记在空格上拆分:
words = s.split(/\s/);
如果您只关心IE9+,那么答案可以缩短:
函数首字母缩略词(文本){
返回文本
.split(/\s/)
.减少(功能(累加器、字){
返回累加器+字字符(0);
}, '');
}
console.log(缩写(“三个字母的缩写”);
您可以用更少的代码实现它。试试这个
s.match(/\b(\w)/g).join("").toUpperCase()
与您的问题无关,但只是一个旁白:务必始终使用var
声明所有变量,否则它们将具有全局作用域。您的索引
变量将是全局的,因此可能会覆盖现有的全局变量-我假设您不是真的打算这么做。(另外,对于循环,您有什么反对意见?)出于好奇,你的问题解决了吗?如果是这样的话,请考虑问任何一个对你帮助最大的答案,然后投票选出你认为有用的。否则,请考虑编辑你的问题,以便我们能进一步帮助你。