- 我正在尝试编写一个代码,其中输入应为abbbcc,输出应为a1b3c2

时间:2017-04-23 10:57:35

标签: javascript jquery html css for-loop

  • 我是js的新手。
  • 我正在尝试编写一个代码,其中输入应为abbbcc,输出应为a1b3c2。
  • 不确定如何获得
  • 提供以下代码
var word = "abbbcc";
var countword = [];

for (i=0; i < word.length; i++) {

    if (word[i] === charAt && word[i] != word[i+1]) {

        countword.push(word[i]);
        countword.push(i++);
    }

    else (word[i] === charAt && word[i] != word[i+1]) {

        countword.push(word[i]);
        for (i=0; i < word.length; i++) {
            if (word[i+1] === word[i+2]) {
                        countword.push(i++);
            }
            else{
                break;
            }
        }

    }


}

console.log("result----->" + countword);

2 个答案:

答案 0 :(得分:2)

可以使用for循环和这样的计数器来完成。

var word = "abbbcc";
var countword = "";
var counter = 1;

for (i=0; i < word.length; i++) {

  if ( word[i] != word[i+1]) {

    // Save the letter and the counter
    countword += word[i]+counter;
    // Reset the counter
    counter=1;

  }else{
    // Increment counter
    counter++;
  }

}

console.log("result-----> " + countword );

答案 1 :(得分:1)

使用Array#reduce的替代解决方案。我已经描述了每一步,我希望你能明白我的观点并理解它是如何运作的。

&#13;
&#13;
var word = "abbbcc".split(''),
    res = '',
    counter = 1;

word.reduce(function(s, a, i, r) {
  if (s !== a) {  //if the succeeding element doesn't match the previous one
    res += s + counter; //concat it to the string + the amount of appearances (counter)
    counter = 1; //reset the counter
  } else {
    counter++; //the succeeding element matches the previous one, increment the counter
  }
  if (i === r.length - 1 && counter > 0) { //if the loop is over
    res += s + counter; //add the last element
  }
  return a;
})

console.log(res);
&#13;
&#13;
&#13;