JavaScript中的缩写生成器。它只获取第一个单词的第一个字母,而不是其他单词。

5

我的代码有什么问题吗?它似乎只获取了第一个字母,而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
}

与您的问题无关,但是顺便提一下:一定要使用“var”声明所有变量,否则它们将具有全局作用域。您的“index”变量将是全局的,因此可能会覆盖现有的全局变量 - 我假设您并不真的想这样做。(另外,您对“for”循环有什么意见吗?) - nnnnnn
出于好奇,你的问题解决了吗?如果是,请考虑选择最有帮助的答案并点赞那些你觉得有用的回答。否则,请考虑编辑你的问题以便我们可以进一步帮助你。 :) - David Thomas
4个回答

6

如果您只关心IE9+,那么答案可以更简短:

function acronym(text) {
  return text
    .split(/\s/)
    .reduce(function(accumulator, word) {
      return accumulator + word.charAt(0);
    }, '');
}

console.log(acronym('three letter acronym'));

如果您可以使用箭头函数,那么它可以更简短:

function acronym(text) {
  return text
    .split(/\s/)
    .reduce((accumulator, word) => accumulator + word.charAt(0), '');
}

console.log(acronym('three letter acronym'));


3
将分隔符添加到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),所以仅返回字符串的第一个字母:

[Separator]指定用于分隔字符串的字符。分隔符被视为字符串或正则表达式。如果省略分隔符,则返回的数组包含一个由整个字符串组成的元素。

参考:


2

您忘记在空格上进行分割:

words = s.split(/\s/);

2
你可以使用更少的代码来实现这个功能。尝试使用以下代码:

s.match(/\b(\w)/g).join("").toUpperCase()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接