问题描述
||
我在代码中缺少什么吗?似乎只抓住第一个字母,而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
}
解决方法
将分隔符添加到
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
}
JS Fiddle演示;
修改了上面的内容,使其更具说明性,并且也具有交互性:JS Fiddle演示。
编辑添加参考和解释:
由于未提供分隔符,因此字符串保持未拆分状态;因此,while
运行正常(因为words.length
等于1
),因此仅返回字符串的第一个字母:
[分隔符]指定用于分隔字符串的字符。分隔符被视为字符串或正则表达式。如果省略了分隔符,则返回的数组包含一个由整个字符串组成的元素。
参考:
split()
,在MDC Docs
,您忘记在空白处拆分:
words = s.split(/\\s/);
,如果您只关心IE9 +,则答案可以更短:
function acronym(text) {
return text
.split(/\\s/)
.reduce(function(accumulator,word) {
return accumulator + word.charAt(0);
},\'\');
}
console.log(acronym(\'three letter acronym\'));