代码之家  ›  专栏  ›  技术社区  ›  code4cash

根据数组+1中的位置重复字符

  •  0
  • code4cash  · 技术社区  · 2 年前

    我试图得到这样的输出:

    ['h', 'ee', 'lll', 'llll', 'ooooo']
    

    目前我的输出是:

    [ 'h', 'ee', 'lll', 'lll', 'ooooo' ]
    

    问题是第二次出现的“l”不会再重复一次,因为我正在计算字母的索引,然后加1,它只计算第一次出现的“l”。 这是我目前掌握的代码,任何帮助都会很好。

    function mumble(string) {
      string.toLowerCase();
      let arrayPush = [];
      let array = string.split("");
      let count = 0;
      let char = [];
      array.map((letter) => {
        count = array.indexOf(letter);
    
        arrayPush.push(letter.repeat(count + 1));
      });
    
      return arrayPush;
    }
    
    console.log(mumble("hello")); 
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   CertainPerformance    2 年前

    不要使用 indexOf ,使用中的第二个参数 .map 回调以确定索引(以及由此确定重复字符串的次数)。

    function mumble(string) {
      string.toLowerCase();
      let arrayPush = [];
      let array = string.split("");
      let count = 0;
      let char = [];
      array.map((letter, i) => {
        arrayPush.push(letter.repeat(i + 1));
      });
    
      return arrayPush;
    }
    
    console.log(mumble("hello")); 
        2
  •  0
  •   Dave Pritlove    2 年前

    而不是申请 .map 到阵列 split 从字符串中,您可以简单地在字符串中循环,使用 .charAt() 字符串方法,并将其 .repeat() 将产品添加到结果数组。

    工作片段:

    console.log(mumble('hELlo'));
    
    function mumble(string) {
    const result = [];
    
    for(let i=0; i<string.length; i++) {
        result.push(string.toLowerCase().charAt(i).repeat(i+1));
    }
    
    return result;
    } // end function mumble;