【问题标题】:How to iteratively build a string如何迭代地构建字符串
【发布时间】:2021-10-31 09:34:50
【问题描述】:

我有一个假设性问题要问你,所以请原谅代码。这个问题是关于我过去的一个测试,一个我想不通的答案,所以它不是“做作业”,只是为了满足我自己的好奇心。不幸的是,我没有保存任何代码。

假设我们有以下输入:

const input = [
                 ["add", "Hello"],
                 ["add", ", how"],
                 ["add", "is it"],
                 ["add", "going today?"]
              ]

如何获得以下输出:

["Hello",
 "Hello, how",
 "Hello, how is it",
 "Hello, how is it going today?"]

我使用了一个输出数组 (output),循环通过 input,在每次迭代中,我将 input[0][1] 推送到 output,毫不奇怪,我构建了一个只有 input[0][i] 的数组。非常粗略的例子:

const output = [];
for (let i = 0; i < input.length; i++ {
    output.push(input[0][i];
}
=> ["Hello", ", how", "is it", "going today?"]

我有一些关于如何去的想法,但不幸的是没时间了。一种想法是遍历“输出”数组并尝试 += 一个字符串,然后遍历该字符串(在构建时)推入最终数组。另一种方式是某种字符串生成器,我想不通。

抱歉,如果这很简单,我还在学习。

【问题讨论】:

  • 在你的例子中你的意思是Hello, how is it going today?吗?你说Hello, how is it going?
  • 我的同事@nick-schmitt 指出,如果有一个前一个或最后一个变量,它会指向前一个输出中的任何内容,并将迭代的元素添加到该变量中,这是可行的。
  • 感谢您指出这一点!我希望修正我的错字。显然我需要更多的咖啡哈哈

标签: javascript arrays string algorithm


【解决方案1】:

你可以做一个简单的循环并在每次迭代时推送字符串

const input = [
  ["add", "Hello"],
  ["add", ", how"],
  ["add", "is it"],
  ["add", "going today?"]
]

function addStr(arr){
  let newArr = []
  let str = ""
  for(let i=0; i<arr.length; i++){
    str = str + arr[i][1]
    newArr.push(str)
  }
  return newArr
}

console.log(addStr(input))

【讨论】:

    【解决方案2】:

    与使用reduce 的另一个答案类似,但我倾向于使用不同的实现,因为它更容易调试 IMO:

    const input = [
      ["add", "Hello"],
      ["add", ", how"],
      ["add", "is it"],
      ["add", "going today?"]
    ]
    
    input.map(([_first, second]) => second)
      .reduce(
        (agg, newStr) => ([
          ...agg,
          (agg[agg.length - 1] + " " + newStr).trim()
        ]),
        [""]
      )
      .slice(1)
    

    这让您非常接近,但唯一需要注意的是,您在 Hello", how" 之间没有空格,这有点难以以编程方式协调。

    【讨论】:

      【解决方案3】:

      使用Array.reduce,然后根据input的当前索引对数组进行切片,最后join切片。

      const input = [
                       ["add", "Hello"],
                       ["add", ", how"],
                       ["add", "is it"],
                       ["add", "going today?"]
                    ]
      console.log(
        input.reduce((pre, cur, index, itself) => {
          pre[index] = itself.slice(0, index + 1).map(item => item[1]).join(' ')
          // pre[index] = itself.slice(0, index + 1).filter(item => item[0] === 'add').map(item => item[1]).join(' ') // if assuming only join the action (verb) is 'add'
          return pre
        }, [])
      )

      【讨论】:

      • 我真的需要更好地学习reduce。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-06
      • 2021-11-23
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      相关资源
      最近更新 更多