【问题标题】:Are there any popular JavaScript libraries that include String.prototype.format or equivalent?是否有任何流行的 JavaScript 库包含 String.prototype.format 或等效的?
【发布时间】:2012-09-27 03:11:04
【问题描述】:

是否有任何流行的 JavaScript 库,如 jQueryUnderscore.js 或类似的实现 'Hello {0}!'.format('World'); 或等效的库?

这是 JavaScript 中的一种不好的做法,而不是不包含它的字符串连接,或者它只是被忽视或被认为过于专业而无法包含在流行的库中?或者,还有其他原因吗?

(请不要用 String.prototype.format 的实现来回答,我要求的是我可能忽略的流行库中的功能。)

【问题讨论】:

标签: javascript


【解决方案1】:

MooTools 在字符串原型上有一个 .substitute 函数,看起来它可以做你想做的事。请参阅:http://mootools.net/docs/core/Types/String#String:substitute

Prototype.js 有一个类似的 .interpolate 函数。见:http://api.prototypejs.org/language/String/prototype/interpolate/

有些人会争辩说,修改原始原型是不好的做法,因为它可能会破坏每个循环的一些常见但格式不正确的内容。

另一方面,Google 的闭包库定义了一个全局 goog.string.format 函数,而不是在字符串原型上,它做同样的事情。见:http://closure-library.googlecode.com/svn/docs/namespace_goog_string.html#goog.string.format

【讨论】:

  • Google 提出了一个很好的观点,尽管他们在他们的文档中说:“不要在简单的情况下使用它而不是内置转换,例如'成本:%.2f',因为它会引入不必要的'Cost: ' + cost.toFixed(2)." 的延迟,这也适用于其他库。
【解决方案2】:

实际上,您可以自己轻松编写这样的方法。由于 ECMAscript 不是一种严格类型的语言,您可以让您的生活更加轻松。示例:

String.prototype.sFormat = function _simpleFormat( map ) {
    var myString    = this.toString(),
        args        = map instanceof Array ? map : Array.prototype.slice.call( arguments );

    while( ~myString.indexOf( '%r' ) ) {
        myString = myString.replace( '%r', args.shift() );
    }

    return myString;
};

从那时起,我们可以像这样走

var foo = "Hello",
    bar = 42;

"%r world, the answer is %r".sFormat( foo, bar ); // "Hello world, the answer is 42"

【讨论】:

  • @ChrisMarisic:尽管如此,我不认为这是一个合理的反对意见。顺便说一句,OP后来添加了斜体部分。我仍然认为这个答案有一些价值,特别是因为它很容易实现。谢谢兄弟;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2015-09-08
  • 2021-01-18
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 2018-06-04
相关资源
最近更新 更多