循环语句-如何在两侧交替。

huangapple go评论58阅读模式
英文:

Loop Statement-how to alternate on both sides

问题

我正在尝试弄清楚如何在我的do..while循环中交替放置字符串"a"两侧的符号"*"。我已经做了一些更改,但最终没有成功 - 我不知道如何获得所需的结果。是否有人有关于我可以做什么的建议?这是我想出的代码:

function padIt(str, n){
  var str = "a", n = "*"
    
  do {
    str = n + str + n;
    n = (n === "*") ? "#" : "*";
  } while (str.length < n)
    
  return str;
}
英文:

I'm trying to figure out how to alternate the "*" symbol on both sides of the string "a" within my do..while loop. I've changed a few things around, but ultimately no dice- I'm stumped on how to get the desired result. Does anyone have any suggestions on what I can do? This is the code I came up with:

function padIt(str,n){
  
  var str=&quot;a&quot;, n= &quot;*&quot;
    
    do{
       str+=n;
      n++;
      
  } while(n&lt;=5)
    
  
    return str;
  }
   

答案1

得分: 1

function padIt(str = "a", n = 0){
    var pad = "*";
    
    do {
        if (n%2 === 0) str+=pad;
        else str = pad + str;
        n++;
    } while(n<=5)
    
    return str;
}

Padding alternation starts at the end when n is odd. You can swap the operations on the if and else statement if you want it to behave the other way.

padIt() // Output: '***a***'
padIt('TESTING',1) // Output: '***TESTING**'
padIt('TESTING',2) // Output: '**TESTING**'
padIt('TESTING',3) // Output: '**TESTING*'
padIt('TESTING',4) // Output: '*TESTING*'
padIt('TESTING',5) // Output: '*TESTING'
padIt('TESTING',6) // Output: 'TESTING*'
padIt('TESTING',7) // Output: '*TESTING'
// ...
英文:
function padIt(str = &quot;a&quot;, n = 0){
    var pad = &quot;*&quot;;
    
    do {
        if (n%2 === 0) str+=pad;
        else str = pad + str;
        n++;
    } while(n&lt;=5)
    
    return str;
}

Padding alternation starts at the end when n is odd. You can swap the operations on the if and else statement if you want it to behave the other way.

padIt() // Output: &#39;***a***&#39;
padIt(&#39;TESTING&#39;,1) // Output: &#39;***TESTING**&#39;
padIt(&#39;TESTING&#39;,2) // Output: &#39;**TESTING**&#39;
padIt(&#39;TESTING&#39;,3) // Output: &#39;**TESTING*&#39;
padIt(&#39;TESTING&#39;,4) // Output: &#39;*TESTING*&#39;
padIt(&#39;TESTING&#39;,5) // Output: &#39;*TESTING&#39;
padIt(&#39;TESTING&#39;,6) // Output: &#39;TESTING*&#39;
padIt(&#39;TESTING&#39;,7) // Output: &#39;*TESTING&#39;
// ...

huangapple
  • 本文由 发表于 2023年2月6日 11:25:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357072.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定