简体   繁体   English

JavaScript - 在一行中格式化多个变量输出

[英]JavaScript - Format Multiple Variable Output in One Line

I've searched as much as I can but can't seem to find what I'm looking for.我已经尽可能多地搜索了,但似乎找不到我要找的东西。

I'm trying to write a simple JS command that will output a formatted string that contains 3 variables that are evenly spaced.我正在尝试编写一个简单的 JS 命令,该命令将输出一个格式化的字符串,其中包含 3 个均匀间隔的变量。

For example, when I did this in C++ I used setw例如,当我在 C++ 中这样做时,我使用了setw

Sample output would be like this:示例输出将是这样的:

var1 = "First"
var2 = "Second"
var3 = "Third"

[VARIABLE 1][VARIABLE 2][VARIABLE 3]
    First      Second      Third

Thanks in advance!提前致谢!

You can use String.prototype.padEnd() and String.prototype.padStart() and length of string to do that.您可以使用String.prototype.padEnd()String.prototype.padStart()以及字符串的长度来做到这一点。

Code below:代码如下:

var1 = "First";
var2 = "Second";
var3 = "Third";

//skip 3 whitespace each string
console.log(
   var1.padStart(3+var1.length)
   +var2.padStart(3+var2.length)
   +var3.padStart(3+var3.length));

Hope it makes your day.希望它能让你开心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM