gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:54:59 25 4
gpt4 key购买 nike

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

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 开源库或编写函数来完成它?)

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

最佳答案

最简单的方法是使用 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);

关于javascript - 如何在 Javascript 中打印出 N 个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12669136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com