【问题标题】:Is there a Javascript method that will achieve concatenation of nested parenthesis?是否有一种 Javascript 方法可以实现嵌套括号的连接?
【发布时间】:2019-06-26 19:07:26
【问题描述】:

我正在尝试从输入创建一个字符串,但以独特的方式格式化。

输入将是单个单词:word1

在第一个输入出现之前,字符串将为空,然后字符串myString 将为+(-word1)

对于第二个输入:word2myString 现在需要如下所示:

    +(-word1+(-word2))

为清楚起见,第三个输入:word3myString 现在将是:

    +(-word1+(-word2+(-word3)))

我相信这需要一些比普通字符串连接更聪明的东西。我宁愿不使用循环。

是否有原生 Javascript(或可能是 JQuery)函数可以完成创建这样的字符串?

这是我所做的

    var myString = '';

    function someFunction()
    { 
     ...

      var inputString = document.getElementById('my-input').value;
      myString = myString + "+(" + "-" + inputString + ")";
    }

然而这正在产生

    +(-word1)+(-word2)

这是有道理的,因为字符串只是在函数中连接,需要发生的事情是一种插入。是否有一种 Javascript 方法可以使这种插入更容易?也许类似于在当前字符串的倒数第二个空格插入新字符串?但是它不是一个数组,所以我不知道这里的最佳实践。

【问题讨论】:

  • 问题是从+(-word1+(-word2))+(-word1+(-word2+(-word3))) 不能通过连接来完成,因为第一个不是第二个的子字符串。您将不得不进行更复杂的操作。如您所述,您必须在前一个字符串中插入新字符串。

标签: javascript string concatenation


【解决方案1】:

不确定这是否是最漂亮的方法,但您可以在单词列表上使用地图......

const words = ['word1', 'word2', 'word3']

let result = '+' + words.map(w => `(-${w}+`).join('').replace(/\+$/, '') + ''.padStart(words.length, ')')

console.log(result)

【讨论】:

    【解决方案2】:

    您查找第一个右括号并替换该值。

    const insert = (s, v) => s ? s.replace(/(?=\))/, `+(-${v})`) : `+(-${v})`;
    
    console.log(['word1', 'word2', 'word3'].reduce(insert, undefined));

    【讨论】:

    • undefined 在这里是什么意思?
    • 它只是一个假值来表示嵌套结构的开始。
    【解决方案3】:

    如果您可以将连续输入存储到数组中,Array.reduceRight() 方法非常适合此问题:

    const words = ['word1', 'word2', 'word3'];
    
    let res = words.reduceRight((s, word) => `+(-${word}${s})`, "");
    
    console.log(res);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    【讨论】:

      【解决方案4】:

      啊,但是你看,普通的字符串连接确实很聪明。

      又快又脏,你需要做的就是在每个之间放置+(- 并附加最后的括号。呵呵……

      arr = ['word1', 'word2', 'word3' ];
      console.log( '+(-' + arr.join('+(-') + ')'.repeat(arr.length) );

      或者使用.map

      arr = ['word1', 'word2', 'word3' ];
      
      console.log(
        arr.map( (e) => `+(-${e}` ) +
        ')'.repeat(arr.length)
      );

      【讨论】:

        【解决方案5】:

        使用计数变量来存储添加了多少单词,然后将字符串切分到只剩下右括号的点。

        插入你的新词

        添加剩余的字符串

        var myString = '';
        var count = 0
            function someFunction()
            { 
             ...
              count++;
              var inputString = document.getElementById('my-input').value;
              myString = myString.slice(0,0-count) + "+(" + "-" + inputString + ")" + myString.slice(0-count);
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-19
          • 2013-04-17
          • 2017-05-07
          • 1970-01-01
          相关资源
          最近更新 更多