【问题标题】:Is there a elegant javascript equivalent of this python code using formatting?是否有一个优雅的 javascript 等价于使用格式化的这个 python 代码?
【发布时间】:2021-05-26 18:33:07
【问题描述】:

是否有与此 python 代码等效的 javascript 代码?我知道你可以使用 ``,但是你怎么能把它和 ... 展开运算符结合起来呢?

'{}{}{} {}{}{}-{}{}{}{}'.format(*array)

数组是长度为 10 的数字列表,预期结果类似于

'123 456-7890'

【问题讨论】:

    标签: javascript arrays string join formatting


    【解决方案1】:

    您可以通过移动数组值来替换。

    const
        format = (pattern, [...array]) =>
            pattern.replace(/\{\}/g, Array.prototype.shift.bind(array));
    
    console.log(format('{}{}{} {}{}{}-{}{}{}{}', [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 2017-07-13
      相关资源
      最近更新 更多