保留 sprintf 输出前导空白的最有效方法
给出以下有效的代码:
for (i=0; i<nLinears; i++) {
for (j=0; j<nLinearPts[i]-1; j++) {
$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f"
,sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen)
.replace(/ /g," "));
}
}
这可以确保当数字从小(更多前导空格)变为大(更少前导空格)时,列间距将保持不变。但是,据我了解,使用 .replace 的正则表达式效率不高,并且由于我在整个应用程序中都有这种结构,因此我需要让它尽可能快地运行。
我相信 jQuery .text() 会满足我的需要,但我还需要 .append() .text() 结果,而且我不知道如何让它们一起工作。
任何建议将不胜感激。
Given the following code which works:
for (i=0; i<nLinears; i++) {
for (j=0; j<nLinearPts[i]-1; j++) {
$wb.upLinearLoad.append('<div>' + sprintf("%5s%8.1f to%7.1f%8.1f"
,sLinearSegName[i][j],fLinearPtBA[i][j],fLinearPtBA[i][j+1],fLen)
.replace(/ /g," "));
}
}
This ensures that as the numbers change from small (more leading spaces) to large (fewer leading spaces), the column spacing will be maintained. However, as I understand it, using the regular expression for the .replace is not efficient, and as I have this kind of structure throughout the application, I need to have it run as fast as possible.
I believe that jQuery .text() will take care my need, but I also need to .append() the .text() result, and I can't figure out how to make them work together.
Any suggestions will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以更新 sprintf() 函数以首先输出不间断空格。
但是您是否真的发现使用正则表达式
.replace()
存在性能问题?我认为你不会有问题。鉴于您似乎有表格数据,为什么不使用?这就是表格的用途。
You could update the
sprintf()
function to output non-breaking spaces in the first place.But have you actually found a performance problem using a regex
.replace()
? I don't think you'll have a problem. Given that you seem to have tabular data, why don't you use a<table>
? This is what tables are for.您可以将它们放入
这通常会使用固定宽度的字体来格式化它们并保留空格,而无需任何额外的工作。
如果这不能完美工作并且您需要替代方案,您可以 查看有关如何在不同上下文中使用预格式化文本的问题。
You could put these in
repeatedly.
<pre>
elements instead of string-replacingThis would (usually) format them with a fixed-width font and preserve spaces without any extra work. The
<pre>
is for preformatted text, which makes sense for what you have here.If this doesn't work perfectly and you need alternatives, you could check out this question about how to use pre-formatted text in different contexts.
我查看了 sprintf(),发现一个简单的单语句更改就产生了我所需要的内容:
感谢 sprintf() 实现的作者使用有意义的变量名称。
I looked at sprintf() and found that a simple one-statement change produced what I needed:
My thanks to the author of the sprintf() implementation for using meaningful variable names.