如何在Javascript中打印出N个空格?

问题描述 投票:5回答:2

在Java语言中,使用打印的方法

console.log("this is %s and %s", foo, bar);

有效,所以它遵循某种C风格,但是没有遵循

console.log("%*s this is %s and %s", 12, foo, bar);

%*s12的位置使其打印出12个空格,如以下问题所示:In Objective-C, how to print out N spaces? (using stringWithCharacters)

是否有一种简短而又快速的方法可以使它简单地在Javascript中运行? (例如,是否不使用sprintf开源库或编写函数来执行此操作?)

Update:,在我的情况下,12实际上是一个变量,例如(i * 4),因此这就是为什么不能将其硬编码为字符串中的空格的原因。

javascript
2个回答
14
投票

最简单的方法是使用Array.join:

console.log("%s this is %s and %s", Array(12 + 1).join(" "), foo, bar);

请注意,您要N + 1作为数组大小。


我知道您说过您不想要函数,但是如果您经常这样做,扩展方法可以变得更干净:

String.prototype.repeat = function(length) {
 return Array(length + 1).join(this);
};

这可以让您做:

console.log("%s this is %s and %s", " ".repeat(12), foo, bar);

0
投票

截至2020年,可能更早,您可以使用' '.repeat(12)

console.log(`${' '.repeat(12)}hello`);
console.log(`${' '.repeat(3)}hello`);
© www.soinside.com 2019 - 2024. All rights reserved.