【问题标题】:javascript array.Join continious srings values into new arrayjavascript array.Join 连续字符串值到新数组中
【发布时间】:2019-11-21 18:51:42
【问题描述】:

我有这个数组 = ["john", "mike", "george", 55, "hello", 344, "goodmorning"] 我想接受这个:[“johnmikegeorge”,55,“hello”,344,“早安”]。我希望有连续的字符串将它们合并为一个。

  var s = ""
    var new_data = []
    var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]
    for (let i = 0; i < pin.length; i++) {
      if (typeof pin[i] === "string") {
        s = s + pin[i]
        new_data.push(s)
      } else {
        s = ""
        new_data.push(pin[i])
      }
    }
    console.log(new_data)

在之前的代码中,我使用这个 ["john", "johnmike", "johnmikegeorge", 55, "hello", 344, "goodmorning"]

【问题讨论】:

    标签: javascript html arrays


    【解决方案1】:

    您可以检查结果集的值和最后一项,如果它们是字符串并添加实际的字符串。

    否则推送项目。这是一个系列的起始字符串或一个数字。

    var array = ["john", "mike", "george", 55, "hello", 344, "goodmorning"],
        result = array.reduce((r, v) => {
            if (typeof v === 'string' && typeof r[r.length - 1] === 'string') {
                r[r.length - 1] += v;
            } else {
                r.push(v);
            }
            return r;
        }, []);
        
    console.log(result);

    【讨论】:

      【解决方案2】:

      我已经修改了您已经拥有的内容以使其正常工作。每当您获得一个数字时,您都会推送您在该数字之前找到的连接字符串,然后推送该数字。 for 循环后的 if 条件是检查推入最后一个数字后是否还有更多字符串。

      var s = "";
      var new_data = []
      var pin = ["john", "mike", "george", 55, "hello", 344, "goodmorning"]
      
      for (let i = 0; i < pin.length; i++) {
        if (typeof pin[i] === "string") {
          s = s + pin[i]
        } else {
          if (s !== "") {
            new_data.push(s);
            s = "";
          }
          new_data.push(pin[i])
        }
      }
      if (s !== "") {
        new_data.push(s);
      }
      
      console.log(new_data)
      

      【讨论】:

        猜你喜欢
        • 2011-05-23
        • 2013-10-03
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-02
        • 2013-06-03
        相关资源
        最近更新 更多