7

在 Javascript 中,使用打印输出的方法

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

有效,所以它遵循一些 C 风格,但它不遵循

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

其中%*sand12是让它打印出 12 个空格,如这个问题: 在 Objective-C 中,如何打印出 N 个空格?(使用 stringWithCharacters)

有没有一种简单快捷的方法让它在 Javascript 中简单地工作?(比如说,不使用sprintf开源库或编写函数来做到这一点?)

更新:,在我的例子中, 12 实际上是一个变量,例如(i * 4),所以这就是为什么它不能是字符串中的硬编码空格。

4

2 回答 2

16

最简单的方法是使用 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);
于 2012-10-01T07:37:25.170 回答
8

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

console.log(`${' '.repeat(12)}hello`);
console.log(`${' '.repeat(3)}hello`);

于 2020-02-24T17:53:06.180 回答