我正在尝试解决来自jshero.net的一个问题。 问题如下:
写一个函数spaces,它接受自然数n并返回n个spaces的字符串。 空格(%1)应返回“”。 我需要使用一个while循环来解决这个挑战。 我能想到的最好的解决办法是:
function spaces(num) {
let mySpaces = '';
while(mySpaces === num) {
mySpaces+= num}
}
}
但它返回以下错误:
spaces(0) does not return '', but undefined.
Test-Error! Correct the error and re-run the tests!
有人知道怎么解决这个吗?
确保返回输出,并从每次迭代的num
中减去:
null
function spaces(num) {
let mySpaces = '';
while (num-- > 0)
mySpaces += ' ';
return mySpaces;
}
console.log(
JSON.stringify(spaces(1)),
'\n',
JSON.stringify(spaces(5))
);