迭代字符串中的单词

时间:2017-02-14 21:04:48

标签: javascript

我试图用下面的代码缩写给定字符串中的所有单词,但是我只能用它来改变每个字符串的第一个单词。我做错了什么?

function abbreviate(string) {
  var words = string.split(" ");
  for (var i = 0; i < words.length; i += 1) {
    var count = words[i].length - 2;
    var last = words[i].charAt(words[i].length - 1);
    return words[i][0] + count + last;
  }
}

1 个答案:

答案 0 :(得分:2)

我认为这解决了你的问题

  function abbreviate(string) {
  var words = string.split(" ");
  var answer = "";
  for (var i = 0; i < words.length; i += 1) {

  var count = words[i].length - 2;
  var last = words[i].charAt(words[i].length - 1);
  answer= answer + words[i][0] + count + last;
  }
return answer;
}