为什么要使用字符串插值?

发布于 2024-11-09 04:16:41 字数 364 浏览 0 评论 0原文

可能的重复:
何时使用 String.Format 与字符串连接?

嗨,我正在为一个开源 Javascript 库编写字符串插值。我刚刚了解字符串插值的概念,有点困惑?为什么我们要这么麻烦地进行字符串插值呢?它有什么优点?

另外,您可以向我指出有关 Javascript 中字符串插值的任何资源吗?与我分享吗?

谢谢

Possible Duplicate:
When is it better to use String.Format vs string concatenation?

Hi, I am writing String Interpolation for an open source Javascript library. I just get to know the concept of String interpolation and am a bit confused? Why do we even go into so much trouble to make String Interpolation? What are its advantages?

Also it there any resources on String interpolation in Javascript that you can point me to? Share with me?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

暖阳 2024-11-16 04:16:41

字符串插值也称为字符串格式化。优点是:

1. 代码清晰,

    "<li>" + "Hello " + name + ". You are visitor number" + visitor_num + "</li>";

更难阅读和编辑

比Java/.Net 方式

String.Format("<li> Hello {0}.  You are visitor number {1}. </li>", name, visitor_num);

python 方式

"<li> Hello %s. You are visitor number %s</li>" % (name, visitor_num)

JavaScript 流行方式

["<li>","Hello",name,". You are visitor number",visitor_num,"</li>"].join(' ')

2. 速度/内存使用

创建多个字符串然后连接它们会使用更多内存,并且比一次创建单个字符串慢。

我曾经写过一个 javascript 字符串格式化程序 -

// simple string builder- usage:   stringFormat("Hello {0}","world"); 
// returns "Hello world"

function stringFormat() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {
          var reg = new RegExp("\\{" + i + "\\}", "gm");
          s = s.replace(reg, arguments[i + 1]);
      }
      return s;
}

String interpolation is also known as string formatting. Advantages are:

1. code clarity

    "<li>" + "Hello " + name + ". You are visitor number" + visitor_num + "</li>";

is harder to read and edit than

Java/.Net way

String.Format("<li> Hello {0}.  You are visitor number {1}. </li>", name, visitor_num);

python way

"<li> Hello %s. You are visitor number %s</li>" % (name, visitor_num)

JavaScript popular way

["<li>","Hello",name,". You are visitor number",visitor_num,"</li>"].join(' ')

2. speed/memory use

Creating multiple strings and then concatenating them uses more memory and is slower than creating a single string one time.

I once wrote a javascript string formatter-

// simple string builder- usage:   stringFormat("Hello {0}","world"); 
// returns "Hello world"

function stringFormat() {
      var s = arguments[0];
      for (var i = 0; i < arguments.length - 1; i++) {
          var reg = new RegExp("\\{" + i + "\\}", "gm");
          s = s.replace(reg, arguments[i + 1]);
      }
      return s;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文