英文:
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="a", n= "*"
do{
str+=n;
n++;
} while(n<=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 = "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'
// ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论