JavaScript等价于Python的format()函数?

2024-10-06 12:48:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Python有一个漂亮的函数来实现这一点:

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy ' + bar3 + ' ' + bar2 ' over the ' + bar1
# The lazy dog jumped over the foobar

进入这个:

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo = 'The lazy {} {} over the {}'.format(bar3, bar2, bar1)
# The lazy dog jumped over the foobar

JavaScript有这样的功能吗?如果不是,我将如何创建一个遵循与Python实现相同语法的?


Tags: the函数功能formatfoojavascriptlazyover
3条回答

另一种方法,使用^{}方法,使用“replacer”函数作为第二个参数:

String.prototype.format = function () {
  var i = 0, args = arguments;
  return this.replace(/{}/g, function () {
    return typeof args[i] != 'undefined' ? args[i++] : '';
  });
};

var bar1 = 'foobar',
    bar2 = 'jumped',
    bar3 = 'dog';

'The lazy {} {} over the {}'.format(bar3, bar2, bar1);
// "The lazy dog jumped over the foobar"

tl;博士

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

为什么仅仅模板字符串是不够的

ES6template strings提供了一个与pythons字符串格式非常相似的特性。但是,在构造字符串之前,必须知道变量:

var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;

为什么格式化?

Python的str.format允许您在之前指定字符串您甚至知道要插入到其中的值,例如:

foo = 'The lazy {} {} over the {}'

bar1 = 'foobar'
bar2 = 'jumped'
bar3 = 'dog'

foo.format(bar3, bar2, bar1)

解决方案

使用arrow function,我们可以优雅地包装模板字符串以供以后使用:

foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`

bar1 = 'foobar';
bar2 = 'jumped';
bar3 = 'dog';

foo(bar3, bar2, bar1)

当然,这也适用于正则函数,但是arrow函数允许我们将其设为一行。这两种功能在大多数浏览器和运行时中都可用:

有一种方法,但不是完全使用格式。

&13;
&13;
var name = "John";
var age = 19;
var message = `My name is ${name} and I am ${age} years old`;
console.log(message);

jsfiddle-link

相关问题 更多 >