gpt4 book ai didi

javascript - Node.js util.format() 作为 String.prototype

转载 作者:行者123 更新时间:2023-11-30 08:54:07 25 4
gpt4 key购买 nike

我正在尝试创建/扩展 node.js util.format函数,以便它可以用作原型(prototype)(例如:“Hello %s”.format(“World”))。但是,我尝试它没有成功。我尝试了以下格式无济于事:

String.prototype.format = function(){return util.format(this, arguments)};

String.prototype.format = function(){return util.format.apply(this, arguments)};

还有

String.prototype.format = function(args){return util.format(this, args)};

这些都不起作用。你知道我做错了什么吗?

谢谢,曼纽尔

最佳答案

我猜你会这样调用它?

"%s: %s".format('key', 'val');

像这样:

String.prototype.format = function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(this.valueOf());
return util.format.apply(util, args);
};

在您的第一个示例中,您只传递了 2 个参数,即格式字符串和参数对象。第二次尝试更接近,但格式的上下文可能应该是 util。您需要将 this 添加到应用于 format 的参数集中。此外,当在字符串上使用 this 时,您使用的是字符串对象,而不是字符串文字,因此您必须使用 valueOf 获取文字版本。

关于javascript - Node.js util.format() 作为 String.prototype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15215473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com