传递数组的nodeJS util.format [英] nodeJS util.format passing an array

查看:89
本文介绍了传递数组的nodeJS util.format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用util.format格式化这样的字符串:

I am using util.format to format a string like this:

util.format('My name is %s %s', ['John', 'Smith']);

第二个参数是一个数组的事实: ['John','Smith'] ,阻止我的代码替换第二个%s.但是我需要将它作为一个数组,因为我不知道字符串可能具有的参数的确切数量.

The fact that the second parameter is an array: ['John', 'Smith'], prevents my code from replacing the second %s. But i need it to be an array because I don't know the exact number of the arguments that the string might have.

您对我的问题有解决方案吗?谢谢你.

Do you have any solution to my problem? Thank's in advance.

包含占位符的字符串不是预定义的静态字符串.我从文件中读取它,因此占位符可能在字符串中的任何位置.出于同样的原因,我也不知道占位符的数量.

The string that contains the placeholders is not a predefined static string. I read it from a file so the placeholders might be anywhere in the string. For the same reason I also don't know the number of placeholders.

推荐答案

如果您不知道该数组中有多少个变量,您如何知道在字符串中定义多少个占位符?

If you don't know how many variables are in that array, how do you know how many placeholders to define in your string ?

我建议您仅使用一个占位符,而只需使用 .join()数组,例如

I'd suggest you only use one placeholder and just .join() the array, like

util.format('My name is %s', ['John', 'Smith'].join(' '));

更新

我想我错了,您可以使用JavaScripts Function.prototype.apply 将参数从Array源传递给函数.看起来像

I guess I got you wrong there, you can make usage of JavaScripts Function.prototype.apply to pass in arguments to a function from an Array source. This could look like

util.format.apply(util,['My name is %s %s','John', 'Smith']);

当然,您还需要预先将占位符字符串 .unshift()放入该数组中.

Of course you would need to .unshift() your placeholder string into that array aswell beforehand.

这篇关于传递数组的nodeJS util.format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆