简体   繁体   English

nodeJS util.format传递数组

[英]nodeJS util.format passing an array

I am using util.format to format a string like this: 我使用util.format来格式化这样的字符串:

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

The fact that the second parameter is an array: ['John', 'Smith'] , prevents my code from replacing the second %s. 第二个参数是一个数组的事实: ['John', 'Smith'] ,阻止我的代码替换第二个%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. 提前致谢。

EDIT: 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 ? 如果您不知道该数组中有多少变量,您如何知道在字符串中定义了多少个占位符?

I'd suggest you only use one placeholder and just .join() the array, like 我建议你只使用一个占位符,只使用 .join()数组

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


Update 更新

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. 我想我错了,你可以利用JavaScripts Function.prototype.apply将参数传递给一个来自Array源的函数。 This could look like 这看起来像

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

Of course you would need to .unshift() your placeholder string into that array aswell beforehand. 当然,你需要将.unshift()占位符字符串放入该数组中。

Do a for-each loop for every string object in table and replace every time one %s. 为表中的每个字符串对象执行for-each循环,并在每次%s时替换。 (for example ['John', 'Smith'] has 2 strings) (例如['John','Smith']有2个字符串)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM