保留 sprintf 输出前导空白的最有效方法

发布于 2024-12-23 14:02:35 字数 531 浏览 2 评论 0原文

给出以下有效的代码:

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,"&nbsp;"));
    }
}

这可以确保当数字从小(更多前导空格)变为大(更少前导空格)时,列间距将保持不变。但是,据我了解,使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

何处潇湘 2024-12-30 14:02:35

您可以更新 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.

羞稚 2024-12-30 14:02:35

您可以将它们放入

 元素中重复字符串替换 

这通常会使用固定宽度的字体来格式化它们并保留空格,而无需任何额外的工作。

 用于预格式化文本,这对于您此处的内容来说很有意义。

如果这不能完美工作并且您需要替代方案,您可以 查看有关如何在不同上下文中使用预格式化文本的问题

You could put these in <pre> elements instead of string-replacing   repeatedly.

This 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.

神经暖 2024-12-30 14:02:35

我查看了 sprintf(),发现一个简单的单语句更改就产生了我所需要的内容:

pad_character = ' ';

感谢 sprintf() 实现的作者使用有意义的变量名称。

I looked at sprintf() and found that a simple one-statement change produced what I needed:

pad_character = ' ';

My thanks to the author of the sprintf() implementation for using meaningful variable names.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文